Fixed spacing
[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 return; // already collated as methods exited
349 }
350
351 $this->collated = array();
352
353 # Estimate profiling overhead
354 $profileCount = count( $this->stack );
355 self::calculateOverhead( $profileCount );
356
357 # First, subtract the overhead!
358 $overheadTotal = $overheadMemory = $overheadInternal = array();
359 foreach ( $this->stack as $entry ) {
360 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
361 $fname = $entry[0];
362 $elapsed = $entry[5] - $entry[2];
363 $memchange = $entry[7] - $entry[4];
364
365 if ( $fname === '-overhead-total' ) {
366 $overheadTotal[] = $elapsed;
367 $overheadMemory[] = max( 0, $memchange );
368 } elseif ( $fname === '-overhead-internal' ) {
369 $overheadInternal[] = $elapsed;
370 }
371 }
372 $overheadTotal = $overheadTotal ?
373 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
374 $overheadMemory = $overheadMemory ?
375 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
376 $overheadInternal = $overheadInternal ?
377 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
378
379 # Collate
380 foreach ( $this->stack as $index => $entry ) {
381 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
382 $fname = $entry[0];
383 $elapsedCpu = $entry[6] - $entry[3];
384 $elapsedReal = $entry[5] - $entry[2];
385 $memchange = $entry[7] - $entry[4];
386 $subcalls = $this->calltreeCount( $this->stack, $index );
387
388 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
389 # Adjust for profiling overhead (except special values with elapsed=0
390 if ( $elapsed ) {
391 $elapsed -= $overheadInternal;
392 $elapsed -= ( $subcalls * $overheadTotal );
393 $memchange -= ( $subcalls * $overheadMemory );
394 }
395 }
396
397 $period = array( 'start' => $entry[2], 'end' => $entry[5],
398 'memory' => $memchange, 'subcalls' => $subcalls );
399 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
400 }
401
402 $this->collated['-overhead-total']['count'] = $profileCount;
403 arsort( $this->collated, SORT_NUMERIC );
404 }
405
406 /**
407 * Returns a list of profiled functions.
408 *
409 * @return string
410 */
411 protected function getFunctionReport() {
412 $this->collateData();
413
414 $width = 140;
415 $nameWidth = $width - 65;
416 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
417 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
418 $prof = "\nProfiling data\n";
419 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
420
421 $total = isset( $this->collated['-total'] )
422 ? $this->collated['-total']['real']
423 : 0;
424
425 foreach ( $this->collated as $fname => $data ) {
426 $calls = $data['count'];
427 $percent = $total ? 100 * $data['real'] / $total : 0;
428 $memory = $data['memory'];
429 $prof .= sprintf( $format,
430 substr( $fname, 0, $nameWidth ),
431 $calls,
432 (float)( $data['real'] * 1000 ),
433 (float)( $data['real'] * 1000 ) / $calls,
434 $percent,
435 $memory,
436 ( $data['min_real'] * 1000.0 ),
437 ( $data['max_real'] * 1000.0 ),
438 $data['overhead']
439 );
440 }
441 $prof .= "\nTotal: $total\n\n";
442
443 return $prof;
444 }
445
446 public function getFunctionStats() {
447 // This method is called before shutdown in the footer method on Skins.
448 // If some outer methods have not yet called wfProfileOut(), work around
449 // that by clearing anything in the work stack to just the "-total" entry.
450 // Collate after doing this so the results do not include profile errors.
451 if ( count( $this->workStack ) > 1 ) {
452 $oldWorkStack = $this->workStack;
453 $this->workStack = array( $this->workStack[0] ); // just the "-total" one
454 } else {
455 $oldWorkStack = null;
456 }
457 $this->collateData();
458 // If this trick is used, then the old work stack is swapped back afterwards
459 // and collateDone is reset to false. This means that logData() will still
460 // make use of all the method data since the missing wfProfileOut() calls
461 // should be made by the time it is called.
462 if ( $oldWorkStack ) {
463 $this->workStack = $oldWorkStack;
464 $this->collateDone = false;
465 }
466
467 $totalCpu = isset( $this->collated['-total'] )
468 ? $this->collated['-total']['cpu']
469 : 0;
470 $totalReal = isset( $this->collated['-total'] )
471 ? $this->collated['-total']['real']
472 : 0;
473 $totalMem = isset( $this->collated['-total'] )
474 ? $this->collated['-total']['memory']
475 : 0;
476
477 $profile = array();
478 foreach ( $this->collated as $fname => $data ) {
479 $profile[] = array(
480 'name' => $fname,
481 'calls' => $data['count'],
482 'real' => $data['real'] * 1000,
483 '%real' => $totalReal ? 100 * $data['real'] / $totalReal : 0,
484 'cpu' => $data['cpu'] * 1000,
485 '%cpu' => $totalCpu ? 100 * $data['cpu'] / $totalCpu : 0,
486 'memory' => $data['memory'],
487 '%memory' => $totalMem ? 100 * $data['memory'] / $totalMem : 0,
488 'min' => $data['min_real'] * 1000,
489 'max' => $data['max_real'] * 1000
490 );
491 }
492
493 return $profile;
494 }
495
496 /**
497 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
498 * @param int $profileCount
499 */
500 protected static function calculateOverhead( $profileCount ) {
501 wfProfileIn( '-overhead-total' );
502 for ( $i = 0; $i < $profileCount; $i++ ) {
503 wfProfileIn( '-overhead-internal' );
504 wfProfileOut( '-overhead-internal' );
505 }
506 wfProfileOut( '-overhead-total' );
507 }
508
509 /**
510 * Counts the number of profiled function calls sitting under
511 * the given point in the call graph. Not the most efficient algo.
512 *
513 * @param array $stack
514 * @param int $start
515 * @return int
516 */
517 protected function calltreeCount( $stack, $start ) {
518 $level = $stack[$start][1];
519 $count = 0;
520 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
521 $count ++;
522 }
523 return $count;
524 }
525
526 /**
527 * Get the initial time of the request, based either on $wgRequestTime or
528 * $wgRUstart. Will return null if not able to find data.
529 *
530 * @param string|bool $metric Metric to use, with the following possibilities:
531 * - user: User CPU time (without system calls)
532 * - cpu: Total CPU time (user and system calls)
533 * - wall (or any other string): elapsed time
534 * - false (default): will fall back to default metric
535 * @return float|null
536 */
537 protected function getTime( $metric = 'wall' ) {
538 if ( $metric === 'cpu' || $metric === 'user' ) {
539 $ru = wfGetRusage();
540 if ( !$ru ) {
541 return 0;
542 }
543 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
544 if ( $metric === 'cpu' ) {
545 # This is the time of system calls, added to the user time
546 # it gives the total CPU time
547 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
548 }
549 return $time;
550 } else {
551 return microtime( true );
552 }
553 }
554
555 /**
556 * Get the initial time of the request, based either on $wgRequestTime or
557 * $wgRUstart. Will return null if not able to find data.
558 *
559 * @param string|bool $metric Metric to use, with the following possibilities:
560 * - user: User CPU time (without system calls)
561 * - cpu: Total CPU time (user and system calls)
562 * - wall (or any other string): elapsed time
563 * - false (default): will fall back to default metric
564 * @return float|null
565 */
566 protected function getInitialTime( $metric = 'wall' ) {
567 global $wgRequestTime, $wgRUstart;
568
569 if ( $metric === 'cpu' || $metric === 'user' ) {
570 if ( !count( $wgRUstart ) ) {
571 return null;
572 }
573
574 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
575 if ( $metric === 'cpu' ) {
576 # This is the time of system calls, added to the user time
577 # it gives the total CPU time
578 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
579 }
580 return $time;
581 } else {
582 if ( empty( $wgRequestTime ) ) {
583 return null;
584 } else {
585 return $wgRequestTime;
586 }
587 }
588 }
589
590 /**
591 * Add an entry in the debug log file
592 *
593 * @param string $s String to output
594 */
595 protected function debug( $s ) {
596 if ( function_exists( 'wfDebug' ) ) {
597 wfDebug( $s );
598 }
599 }
600
601 /**
602 * Add an entry in the debug log group
603 *
604 * @param string $group Group to send the message to
605 * @param string $s String to output
606 */
607 protected function debugGroup( $group, $s ) {
608 if ( function_exists( 'wfDebugLog' ) ) {
609 wfDebugLog( $group, $s );
610 }
611 }
612 }