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