Merge "Removed some unnecessary code in LocalFileDeleteBatch"
[lhc/web/wiklou.git] / includes / profiler / ProfilerStandard.php
1 <?php
2 /**
3 * Common implementation class for profiling.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Profiler
22 */
23
24 /**
25 * Standard profiler that tracks real time, cpu time, and memory deltas
26 *
27 * This supports profile reports, the debug toolbar, and high-contention
28 * DB query warnings. This does not persist the profiling data though.
29 *
30 * @ingroup Profiler
31 * @since 1.24
32 */
33 class ProfilerStandard extends Profiler {
34 /** @var array List of resolved profile calls with start/end data */
35 protected $stack = array();
36 /** @var array Queue of open profile calls with start data */
37 protected $workStack = array();
38
39 /** @var array Map of (function name => aggregate data array) */
40 protected $collated = array();
41 /** @var bool */
42 protected $collateDone = false;
43 /** @var bool Whether to collect the full stack trace or just aggregates */
44 protected $collateOnly = true;
45 /** @var array Cache of a standard broken collation entry */
46 protected $errorEntry;
47
48 /**
49 * @param array $params
50 * - initTotal : set to false to omit -total/-setup entries (which use request start time)
51 */
52 public function __construct( array $params ) {
53 parent::__construct( $params );
54
55 if ( !isset( $params['initTotal'] ) || $params['initTotal'] ) {
56 $this->addInitialStack();
57 }
58 }
59
60 /**
61 * Add the inital item in the stack.
62 */
63 protected function addInitialStack() {
64 $this->errorEntry = $this->getErrorEntry();
65
66 $initialTime = $this->getInitialTime( 'wall' );
67 $initialCpu = $this->getInitialTime( 'cpu' );
68 if ( $initialTime !== null && $initialCpu !== null ) {
69 $this->workStack[] = array( '-total', 0, $initialTime, $initialCpu, 0 );
70 if ( $this->collateOnly ) {
71 $this->workStack[] = array( '-setup', 1, $initialTime, $initialCpu, 0 );
72 $this->profileOut( '-setup' );
73 } else {
74 $this->stack[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
75 $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
76 }
77 } else {
78 $this->profileIn( '-total' );
79 }
80 }
81
82 /**
83 * @return array Initial collation entry
84 */
85 protected function getZeroEntry() {
86 return array(
87 'cpu' => 0.0,
88 'cpu_sq' => 0.0,
89 'real' => 0.0,
90 'real_sq' => 0.0,
91 'memory' => 0,
92 'count' => 0,
93 'min_cpu' => 0.0,
94 'max_cpu' => 0.0,
95 'min_real' => 0.0,
96 'max_real' => 0.0,
97 'periods' => array(), // not filled if collateOnly
98 'overhead' => 0 // not filled if collateOnly
99 );
100 }
101
102 /**
103 * @return array Initial collation entry for errors
104 */
105 protected function getErrorEntry() {
106 $entry = $this->getZeroEntry();
107 $entry['count'] = 1;
108 return $entry;
109 }
110
111 /**
112 * Update the collation entry for a given method name
113 *
114 * @param string $name
115 * @param float $elapsedCpu
116 * @param float $elapsedReal
117 * @param int $memChange
118 * @param int $subcalls
119 * @param array|null $period Map of ('start','end','memory','subcalls')
120 */
121 protected function updateEntry(
122 $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
123 ) {
124 $entry =& $this->collated[$name];
125 if ( !is_array( $entry ) ) {
126 $entry = $this->getZeroEntry();
127 $this->collated[$name] =& $entry;
128 }
129 $entry['cpu'] += $elapsedCpu;
130 $entry['cpu_sq'] += $elapsedCpu * $elapsedCpu;
131 $entry['real'] += $elapsedReal;
132 $entry['real_sq'] += $elapsedReal * $elapsedReal;
133 $entry['memory'] += $memChange > 0 ? $memChange : 0;
134 $entry['count']++;
135 $entry['min_cpu'] = $elapsedCpu < $entry['min_cpu'] ? $elapsedCpu : $entry['min_cpu'];
136 $entry['max_cpu'] = $elapsedCpu > $entry['max_cpu'] ? $elapsedCpu : $entry['max_cpu'];
137 $entry['min_real'] = $elapsedReal < $entry['min_real'] ? $elapsedReal : $entry['min_real'];
138 $entry['max_real'] = $elapsedReal > $entry['max_real'] ? $elapsedReal : $entry['max_real'];
139 // Apply optional fields
140 $entry['overhead'] += $subcalls;
141 if ( $period ) {
142 $entry['periods'][] = $period;
143 }
144 }
145
146 /**
147 * Called by wfProfieIn()
148 *
149 * @param string $functionname
150 */
151 public function profileIn( $functionname ) {
152 global $wgDebugFunctionEntry;
153
154 if ( $wgDebugFunctionEntry ) {
155 $this->debug( str_repeat( ' ', count( $this->workStack ) ) .
156 'Entering ' . $functionname . "\n" );
157 }
158
159 $this->workStack[] = array(
160 $functionname,
161 count( $this->workStack ),
162 $this->getTime( 'time' ),
163 $this->getTime( 'cpu' ),
164 memory_get_usage()
165 );
166 }
167
168 /**
169 * Called by wfProfieOut()
170 *
171 * @param string $functionname
172 */
173 public function profileOut( $functionname ) {
174 global $wgDebugFunctionEntry;
175
176 if ( $wgDebugFunctionEntry ) {
177 $this->debug( str_repeat( ' ', count( $this->workStack ) - 1 ) .
178 'Exiting ' . $functionname . "\n" );
179 }
180
181 $item = array_pop( $this->workStack );
182 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
183
184 if ( $item === null ) {
185 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
186 } else {
187 if ( $functionname === 'close' ) {
188 if ( $ofname !== '-total' ) {
189 $message = "Profile section ended by close(): {$ofname}";
190 $this->debugGroup( 'profileerror', $message );
191 if ( $this->collateOnly ) {
192 $this->collated[$message] = $this->errorEntry;
193 } else {
194 $this->stack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
195 }
196 }
197 $functionname = $ofname;
198 } elseif ( $ofname !== $functionname ) {
199 $message = "Profiling error: in({$ofname}), out($functionname)";
200 $this->debugGroup( 'profileerror', $message );
201 if ( $this->collateOnly ) {
202 $this->collated[$message] = $this->errorEntry;
203 } else {
204 $this->stack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
205 }
206 }
207 $realTime = $this->getTime( 'wall' );
208 $cpuTime = $this->getTime( 'cpu' );
209 if ( $this->collateOnly ) {
210 $elapsedcpu = $cpuTime - $octime;
211 $elapsedreal = $realTime - $ortime;
212 $memchange = memory_get_usage() - $omem;
213 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
214 } else {
215 $this->stack[] = array_merge( $item,
216 array( $realTime, $cpuTime, memory_get_usage() ) );
217 }
218 }
219 }
220
221 public function scopedProfileIn( $section ) {
222 $this->profileIn( $section );
223
224 $that = $this;
225 return new ScopedCallback( function () use ( $that, $section ) {
226 $that->profileOut( $section );
227 } );
228 }
229
230 /**
231 * Close opened profiling sections
232 */
233 public function close() {
234 while ( count( $this->workStack ) ) {
235 $this->profileOut( 'close' );
236 }
237 }
238
239 /**
240 * Returns a profiling output to be stored in debug file
241 *
242 * @return string
243 */
244 public function getOutput() {
245 global $wgDebugFunctionEntry, $wgProfileCallTree;
246
247 $wgDebugFunctionEntry = false; // hack
248
249 if ( !count( $this->stack ) && !count( $this->collated ) ) {
250 return "No profiling output\n";
251 }
252
253 if ( $wgProfileCallTree ) {
254 return $this->getCallTree();
255 } else {
256 return $this->getFunctionReport();
257 }
258 }
259
260 /**
261 * Returns a tree of function call instead of a list of functions
262 * @return string
263 */
264 protected function getCallTree() {
265 return implode( '', array_map(
266 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack )
267 ) );
268 }
269
270 /**
271 * Recursive function the format the current profiling array into a tree
272 *
273 * @param array $stack Profiling array
274 * @return array
275 */
276 protected function remapCallTree( array $stack ) {
277 if ( count( $stack ) < 2 ) {
278 return $stack;
279 }
280 $outputs = array();
281 for ( $max = count( $stack ) - 1; $max > 0; ) {
282 /* Find all items under this entry */
283 $level = $stack[$max][1];
284 $working = array();
285 for ( $i = $max -1; $i >= 0; $i-- ) {
286 if ( $stack[$i][1] > $level ) {
287 $working[] = $stack[$i];
288 } else {
289 break;
290 }
291 }
292 $working = $this->remapCallTree( array_reverse( $working ) );
293 $output = array();
294 foreach ( $working as $item ) {
295 array_push( $output, $item );
296 }
297 array_unshift( $output, $stack[$max] );
298 $max = $i;
299
300 array_unshift( $outputs, $output );
301 }
302 $final = array();
303 foreach ( $outputs as $output ) {
304 foreach ( $output as $item ) {
305 $final[] = $item;
306 }
307 }
308 return $final;
309 }
310
311 /**
312 * Callback to get a formatted line for the call tree
313 * @param array $entry
314 * @return string
315 */
316 protected function getCallTreeLine( $entry ) {
317 list( $fname, $level, $startreal, , , $endreal ) = $entry;
318 $delta = $endreal - $startreal;
319 $space = str_repeat( ' ', $level );
320 # The ugly double sprintf is to work around a PHP bug,
321 # which has been fixed in recent releases.
322 return sprintf( "%10s %s %s\n",
323 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
324 }
325
326 /**
327 * Return the collated data, collating first if need be
328 * @return array
329 */
330 public function getCollatedData() {
331 if ( !$this->collateDone ) {
332 $this->collateData();
333 }
334 return $this->collated;
335 }
336
337 /**
338 * Populate collated
339 */
340 protected function collateData() {
341 if ( $this->collateDone ) {
342 return;
343 }
344 $this->collateDone = true;
345 $this->close(); // set "-total" entry
346
347 if ( $this->collateOnly ) {
348 // already collated as methods exited
349 $this->sortCollated();
350 return;
351 }
352
353 $this->collated = array();
354
355 # Estimate profiling overhead
356 $profileCount = count( $this->stack );
357 self::calculateOverhead( $profileCount );
358
359 # First, subtract the overhead!
360 $overheadTotal = $overheadMemory = $overheadInternal = array();
361 foreach ( $this->stack as $entry ) {
362 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
363 $fname = $entry[0];
364 $elapsed = $entry[5] - $entry[2];
365 $memchange = $entry[7] - $entry[4];
366
367 if ( $fname === '-overhead-total' ) {
368 $overheadTotal[] = $elapsed;
369 $overheadMemory[] = max( 0, $memchange );
370 } elseif ( $fname === '-overhead-internal' ) {
371 $overheadInternal[] = $elapsed;
372 }
373 }
374 $overheadTotal = $overheadTotal ?
375 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
376 $overheadMemory = $overheadMemory ?
377 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
378 $overheadInternal = $overheadInternal ?
379 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
380
381 # Collate
382 foreach ( $this->stack as $index => $entry ) {
383 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
384 $fname = $entry[0];
385 $elapsedCpu = $entry[6] - $entry[3];
386 $elapsedReal = $entry[5] - $entry[2];
387 $memchange = $entry[7] - $entry[4];
388 $subcalls = $this->calltreeCount( $this->stack, $index );
389
390 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
391 # Adjust for profiling overhead (except special values with elapsed=0
392 if ( $elapsed ) {
393 $elapsed -= $overheadInternal;
394 $elapsed -= ( $subcalls * $overheadTotal );
395 $memchange -= ( $subcalls * $overheadMemory );
396 }
397 }
398
399 $period = array( 'start' => $entry[2], 'end' => $entry[5],
400 'memory' => $memchange, 'subcalls' => $subcalls );
401 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
402 }
403
404 $this->collated['-overhead-total']['count'] = $profileCount;
405 $this->sortCollated();
406 }
407
408 protected function sortCollated() {
409 uksort( $this->collated, function ( $a, $b ) {
410 $ca = $this->collated[$a]['real'];
411 $cb = $this->collated[$b]['real'];
412 if ( $ca > $cb ) {
413 return -1;
414 } elseif ( $cb > $ca ) {
415 return 1;
416 } else {
417 return 0;
418 }
419 } );
420 }
421
422 /**
423 * Returns a list of profiled functions.
424 *
425 * @return string
426 */
427 protected function getFunctionReport() {
428 $this->collateData();
429
430 $width = 140;
431 $nameWidth = $width - 65;
432 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
433 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
434 $prof = "\nProfiling data\n";
435 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
436
437 $total = isset( $this->collated['-total'] )
438 ? $this->collated['-total']['real']
439 : 0;
440
441 foreach ( $this->collated as $fname => $data ) {
442 $calls = $data['count'];
443 $percent = $total ? 100 * $data['real'] / $total : 0;
444 $memory = $data['memory'];
445 $prof .= sprintf( $format,
446 substr( $fname, 0, $nameWidth ),
447 $calls,
448 (float)( $data['real'] * 1000 ),
449 (float)( $data['real'] * 1000 ) / $calls,
450 $percent,
451 $memory,
452 ( $data['min_real'] * 1000.0 ),
453 ( $data['max_real'] * 1000.0 ),
454 $data['overhead']
455 );
456 }
457 $prof .= "\nTotal: $total\n\n";
458
459 return $prof;
460 }
461
462 public function getFunctionStats() {
463 // This method is called before shutdown in the footer method on Skins.
464 // If some outer methods have not yet called wfProfileOut(), work around
465 // that by clearing anything in the work stack to just the "-total" entry.
466 // Collate after doing this so the results do not include profile errors.
467 if ( count( $this->workStack ) > 1 ) {
468 $oldWorkStack = $this->workStack;
469 $this->workStack = array( $this->workStack[0] ); // just the "-total" one
470 } else {
471 $oldWorkStack = null;
472 }
473 $this->collateData();
474 // If this trick is used, then the old work stack is swapped back afterwards
475 // and collateDone is reset to false. This means that logData() will still
476 // make use of all the method data since the missing wfProfileOut() calls
477 // should be made by the time it is called.
478 if ( $oldWorkStack ) {
479 $this->workStack = $oldWorkStack;
480 $this->collateDone = false;
481 }
482
483 $totalCpu = isset( $this->collated['-total'] )
484 ? $this->collated['-total']['cpu']
485 : 0;
486 $totalReal = isset( $this->collated['-total'] )
487 ? $this->collated['-total']['real']
488 : 0;
489 $totalMem = isset( $this->collated['-total'] )
490 ? $this->collated['-total']['memory']
491 : 0;
492
493 $profile = array();
494 foreach ( $this->collated as $fname => $data ) {
495 $profile[] = array(
496 'name' => $fname,
497 'calls' => $data['count'],
498 'real' => $data['real'] * 1000,
499 '%real' => $totalReal ? 100 * $data['real'] / $totalReal : 0,
500 'cpu' => $data['cpu'] * 1000,
501 '%cpu' => $totalCpu ? 100 * $data['cpu'] / $totalCpu : 0,
502 'memory' => $data['memory'],
503 '%memory' => $totalMem ? 100 * $data['memory'] / $totalMem : 0,
504 'min_real' => $data['min_real'] * 1000,
505 'max_real' => $data['max_real'] * 1000
506 );
507 }
508
509 return $profile;
510 }
511
512 /**
513 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
514 * @param int $profileCount
515 */
516 protected static function calculateOverhead( $profileCount ) {
517 wfProfileIn( '-overhead-total' );
518 for ( $i = 0; $i < $profileCount; $i++ ) {
519 wfProfileIn( '-overhead-internal' );
520 wfProfileOut( '-overhead-internal' );
521 }
522 wfProfileOut( '-overhead-total' );
523 }
524
525 /**
526 * Counts the number of profiled function calls sitting under
527 * the given point in the call graph. Not the most efficient algo.
528 *
529 * @param array $stack
530 * @param int $start
531 * @return int
532 */
533 protected function calltreeCount( $stack, $start ) {
534 $level = $stack[$start][1];
535 $count = 0;
536 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
537 $count ++;
538 }
539 return $count;
540 }
541
542 /**
543 * Get the initial time of the request, based either on $wgRequestTime or
544 * $wgRUstart. Will return null if not able to find data.
545 *
546 * @param string|bool $metric Metric to use, with the following possibilities:
547 * - user: User CPU time (without system calls)
548 * - cpu: Total CPU time (user and system calls)
549 * - wall (or any other string): elapsed time
550 * - false (default): will fall back to default metric
551 * @return float|null
552 */
553 protected function getTime( $metric = 'wall' ) {
554 if ( $metric === 'cpu' || $metric === 'user' ) {
555 $ru = wfGetRusage();
556 if ( !$ru ) {
557 return 0;
558 }
559 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
560 if ( $metric === 'cpu' ) {
561 # This is the time of system calls, added to the user time
562 # it gives the total CPU time
563 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
564 }
565 return $time;
566 } else {
567 return microtime( true );
568 }
569 }
570
571 /**
572 * Get the initial time of the request, based either on $wgRequestTime or
573 * $wgRUstart. Will return null if not able to find data.
574 *
575 * @param string|bool $metric Metric to use, with the following possibilities:
576 * - user: User CPU time (without system calls)
577 * - cpu: Total CPU time (user and system calls)
578 * - wall (or any other string): elapsed time
579 * - false (default): will fall back to default metric
580 * @return float|null
581 */
582 protected function getInitialTime( $metric = 'wall' ) {
583 global $wgRequestTime, $wgRUstart;
584
585 if ( $metric === 'cpu' || $metric === 'user' ) {
586 if ( !count( $wgRUstart ) ) {
587 return null;
588 }
589
590 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
591 if ( $metric === 'cpu' ) {
592 # This is the time of system calls, added to the user time
593 # it gives the total CPU time
594 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
595 }
596 return $time;
597 } else {
598 if ( empty( $wgRequestTime ) ) {
599 return null;
600 } else {
601 return $wgRequestTime;
602 }
603 }
604 }
605
606 /**
607 * Add an entry in the debug log file
608 *
609 * @param string $s String to output
610 */
611 protected function debug( $s ) {
612 if ( function_exists( 'wfDebug' ) ) {
613 wfDebug( $s );
614 }
615 }
616
617 /**
618 * Add an entry in the debug log group
619 *
620 * @param string $group Group to send the message to
621 * @param string $s String to output
622 */
623 protected function debugGroup( $group, $s ) {
624 if ( function_exists( 'wfDebugLog' ) ) {
625 wfDebugLog( $group, $s );
626 }
627 }
628 }