3 * Common implementation class for profiling.
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.
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.
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
25 * Standard profiler that tracks real time, cpu time, and memory deltas
27 * This supports profile reports, the debug toolbar, and high-contention
28 * DB query warnings. This does not persist the profiling data though.
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();
39 /** @var array Map of (function name => aggregate data array) */
40 protected $collated = array();
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;
49 * @param array $params
50 * - initTotal : set to false to omit -total/-setup entries (which use request start time)
52 public function __construct( array $params ) {
53 parent
::__construct( $params );
55 if ( !isset( $params['initTotal'] ) ||
$params['initTotal'] ) {
56 $this->addInitialStack();
61 * Return whether this a stub profiler
65 public function isStub() {
70 * Add the inital item in the stack.
72 protected function addInitialStack() {
73 $this->errorEntry
= $this->getErrorEntry();
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' );
83 $this->stack
[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
84 $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
87 $this->profileIn( '-total' );
92 * @return array Initial collation entry
94 protected function getZeroEntry() {
106 'periods' => array(), // not filled if collateOnly
107 'overhead' => 0 // not filled if collateOnly
112 * @return array Initial collation entry for errors
114 protected function getErrorEntry() {
115 $entry = $this->getZeroEntry();
121 * Update the collation entry for a given method name
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')
130 protected function updateEntry(
131 $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
133 $entry =& $this->collated
[$name];
134 if ( !is_array( $entry ) ) {
135 $entry = $this->getZeroEntry();
136 $this->collated
[$name] =& $entry;
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;
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;
151 $entry['periods'][] = $period;
156 * Called by wfProfieIn()
158 * @param string $functionname
160 public function profileIn( $functionname ) {
161 global $wgDebugFunctionEntry;
163 if ( $wgDebugFunctionEntry ) {
164 $this->debug( str_repeat( ' ', count( $this->workStack
) ) .
165 'Entering ' . $functionname . "\n" );
168 $this->workStack
[] = array(
170 count( $this->workStack
),
171 $this->getTime( 'time' ),
172 $this->getTime( 'cpu' ),
178 * Called by wfProfieOut()
180 * @param string $functionname
182 public function profileOut( $functionname ) {
183 global $wgDebugFunctionEntry;
185 if ( $wgDebugFunctionEntry ) {
186 $this->debug( str_repeat( ' ', count( $this->workStack
) - 1 ) .
187 'Exiting ' . $functionname . "\n" );
190 $item = array_pop( $this->workStack
);
191 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
193 if ( $item === null ) {
194 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
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
;
203 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
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
;
213 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
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 );
224 $this->stack
[] = array_merge( $item,
225 array( $realTime, $cpuTime, memory_get_usage() ) );
230 public function scopedProfileIn( $section ) {
231 $this->profileIn( $section );
234 return new ScopedCallback( function() use ( $that, $section ) {
235 $that->profileOut( $section );
240 * Close opened profiling sections
242 public function close() {
243 while ( count( $this->workStack
) ) {
244 $this->profileOut( 'close' );
249 * Returns a profiling output to be stored in debug file
253 public function getOutput() {
254 global $wgDebugFunctionEntry, $wgProfileCallTree;
256 $wgDebugFunctionEntry = false; // hack
258 if ( !count( $this->stack
) && !count( $this->collated
) ) {
259 return "No profiling output\n";
262 if ( $wgProfileCallTree ) {
263 return $this->getCallTree();
265 return $this->getFunctionReport();
270 * Returns a tree of function call instead of a list of functions
273 protected function getCallTree() {
274 return implode( '', array_map(
275 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack
)
280 * Recursive function the format the current profiling array into a tree
282 * @param array $stack Profiling array
285 protected function remapCallTree( array $stack ) {
286 if ( count( $stack ) < 2 ) {
290 for ( $max = count( $stack ) - 1; $max > 0; ) {
291 /* Find all items under this entry */
292 $level = $stack[$max][1];
294 for ( $i = $max -1; $i >= 0; $i-- ) {
295 if ( $stack[$i][1] > $level ) {
296 $working[] = $stack[$i];
301 $working = $this->remapCallTree( array_reverse( $working ) );
303 foreach ( $working as $item ) {
304 array_push( $output, $item );
306 array_unshift( $output, $stack[$max] );
309 array_unshift( $outputs, $output );
312 foreach ( $outputs as $output ) {
313 foreach ( $output as $item ) {
321 * Callback to get a formatted line for the call tree
322 * @param array $entry
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 );
336 * Return the collated data, collating first if need be
339 public function getCollatedData() {
340 if ( !$this->collateDone
) {
341 $this->collateData();
343 return $this->collated
;
349 protected function collateData() {
350 if ( $this->collateDone
) {
353 $this->collateDone
= true;
354 $this->close(); // set "-total" entry
356 if ( $this->collateOnly
) {
357 return; // already collated as methods exited
360 $this->collated
= array();
362 # Estimate profiling overhead
363 $profileCount = count( $this->stack
);
364 self
::calculateOverhead( $profileCount );
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)
371 $elapsed = $entry[5] - $entry[2];
372 $memchange = $entry[7] - $entry[4];
374 if ( $fname === '-overhead-total' ) {
375 $overheadTotal[] = $elapsed;
376 $overheadMemory[] = max( 0, $memchange );
377 } elseif ( $fname === '-overhead-internal' ) {
378 $overheadInternal[] = $elapsed;
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;
389 foreach ( $this->stack
as $index => $entry ) {
390 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
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 );
397 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
398 # Adjust for profiling overhead (except special values with elapsed=0
400 $elapsed -= $overheadInternal;
401 $elapsed -= ( $subcalls * $overheadTotal );
402 $memchange -= ( $subcalls * $overheadMemory );
406 $period = array( 'start' => $entry[2], 'end' => $entry[5],
407 'memory' => $memchange, 'subcalls' => $subcalls );
408 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
411 $this->collated
['-overhead-total']['count'] = $profileCount;
412 arsort( $this->collated
, SORT_NUMERIC
);
416 * Returns a list of profiled functions.
420 protected function getFunctionReport() {
421 $this->collateData();
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' );
430 $total = isset( $this->collated
['-total'] )
431 ?
$this->collated
['-total']['real']
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 ),
441 (float)( $data['real'] * 1000 ),
442 (float)( $data['real'] * 1000 ) / $calls,
445 ( $data['min_real'] * 1000.0 ),
446 ( $data['max_real'] * 1000.0 ),
450 $prof .= "\nTotal: $total\n\n";
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
464 $oldWorkStack = null;
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;
476 $totalCpu = isset( $this->collated
['-total'] )
477 ?
$this->collated
['-total']['cpu']
479 $totalReal = isset( $this->collated
['-total'] )
480 ?
$this->collated
['-total']['real']
482 $totalMem = isset( $this->collated
['-total'] )
483 ?
$this->collated
['-total']['memory']
487 foreach ( $this->collated
as $fname => $data ) {
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
506 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
507 * @param int $profileCount
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' );
515 wfProfileOut( '-overhead-total' );
519 * Counts the number of profiled function calls sitting under
520 * the given point in the call graph. Not the most efficient algo.
522 * @param array $stack
526 protected function calltreeCount( $stack, $start ) {
527 $level = $stack[$start][1];
529 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
536 * Get the initial time of the request, based either on $wgRequestTime or
537 * $wgRUstart. Will return null if not able to find data.
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
546 protected function getTime( $metric = 'wall' ) {
547 if ( $metric === 'cpu' ||
$metric === 'user' ) {
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
;
560 return microtime( true );
565 * Get the initial time of the request, based either on $wgRequestTime or
566 * $wgRUstart. Will return null if not able to find data.
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
575 protected function getInitialTime( $metric = 'wall' ) {
576 global $wgRequestTime, $wgRUstart;
578 if ( $metric === 'cpu' ||
$metric === 'user' ) {
579 if ( !count( $wgRUstart ) ) {
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
;
591 if ( empty( $wgRequestTime ) ) {
594 return $wgRequestTime;
600 * Add an entry in the debug log file
602 * @param string $s String to output
604 protected function debug( $s ) {
605 if ( function_exists( 'wfDebug' ) ) {
611 * Add an entry in the debug log group
613 * @param string $group Group to send the message to
614 * @param string $s String to output
616 protected function debugGroup( $group, $s ) {
617 if ( function_exists( 'wfDebugLog' ) ) {
618 wfDebugLog( $group, $s );