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() ) );
231 * Close opened profiling sections
233 public function close() {
234 while ( count( $this->workStack
) ) {
235 $this->profileOut( 'close' );
240 * Log the data to some store or even the page output
242 public function logData() {
243 /* Implement in subclasses */
247 * Returns a profiling output to be stored in debug file
251 public function getOutput() {
252 global $wgDebugFunctionEntry, $wgProfileCallTree;
254 $wgDebugFunctionEntry = false; // hack
256 if ( !count( $this->stack
) && !count( $this->collated
) ) {
257 return "No profiling output\n";
260 if ( $wgProfileCallTree ) {
261 return $this->getCallTree();
263 return $this->getFunctionReport();
268 * Returns a tree of function call instead of a list of functions
271 protected function getCallTree() {
272 return implode( '', array_map(
273 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack
)
278 * Recursive function the format the current profiling array into a tree
280 * @param array $stack Profiling array
283 protected function remapCallTree( array $stack ) {
284 if ( count( $stack ) < 2 ) {
288 for ( $max = count( $stack ) - 1; $max > 0; ) {
289 /* Find all items under this entry */
290 $level = $stack[$max][1];
292 for ( $i = $max -1; $i >= 0; $i-- ) {
293 if ( $stack[$i][1] > $level ) {
294 $working[] = $stack[$i];
299 $working = $this->remapCallTree( array_reverse( $working ) );
301 foreach ( $working as $item ) {
302 array_push( $output, $item );
304 array_unshift( $output, $stack[$max] );
307 array_unshift( $outputs, $output );
310 foreach ( $outputs as $output ) {
311 foreach ( $output as $item ) {
319 * Callback to get a formatted line for the call tree
320 * @param array $entry
323 protected function getCallTreeLine( $entry ) {
324 list( $fname, $level, $startreal, , , $endreal ) = $entry;
325 $delta = $endreal - $startreal;
326 $space = str_repeat( ' ', $level );
327 # The ugly double sprintf is to work around a PHP bug,
328 # which has been fixed in recent releases.
329 return sprintf( "%10s %s %s\n",
330 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
336 protected function collateData() {
337 if ( $this->collateDone
) {
340 $this->collateDone
= true;
341 $this->close(); // set "-total" entry
343 if ( $this->collateOnly
) {
344 return; // already collated as methods exited
347 $this->collated
= array();
349 # Estimate profiling overhead
350 $profileCount = count( $this->stack
);
351 self
::calculateOverhead( $profileCount );
353 # First, subtract the overhead!
354 $overheadTotal = $overheadMemory = $overheadInternal = array();
355 foreach ( $this->stack
as $entry ) {
356 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
358 $elapsed = $entry[5] - $entry[2];
359 $memchange = $entry[7] - $entry[4];
361 if ( $fname === '-overhead-total' ) {
362 $overheadTotal[] = $elapsed;
363 $overheadMemory[] = max( 0, $memchange );
364 } elseif ( $fname === '-overhead-internal' ) {
365 $overheadInternal[] = $elapsed;
368 $overheadTotal = $overheadTotal ?
369 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
370 $overheadMemory = $overheadMemory ?
371 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
372 $overheadInternal = $overheadInternal ?
373 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
376 foreach ( $this->stack
as $index => $entry ) {
377 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
379 $elapsedCpu = $entry[6] - $entry[3];
380 $elapsedReal = $entry[5] - $entry[2];
381 $memchange = $entry[7] - $entry[4];
382 $subcalls = $this->calltreeCount( $this->stack
, $index );
384 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
385 # Adjust for profiling overhead (except special values with elapsed=0
387 $elapsed -= $overheadInternal;
388 $elapsed -= ( $subcalls * $overheadTotal );
389 $memchange -= ( $subcalls * $overheadMemory );
393 $period = array( 'start' => $entry[2], 'end' => $entry[5],
394 'memory' => $memchange, 'subcalls' => $subcalls );
395 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
398 $this->collated
['-overhead-total']['count'] = $profileCount;
399 arsort( $this->collated
, SORT_NUMERIC
);
403 * Returns a list of profiled functions.
407 protected function getFunctionReport() {
408 $this->collateData();
411 $nameWidth = $width - 65;
412 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
413 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
414 $prof = "\nProfiling data\n";
415 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
417 $total = isset( $this->collated
['-total'] )
418 ?
$this->collated
['-total']['real']
421 foreach ( $this->collated
as $fname => $data ) {
422 $calls = $data['count'];
423 $percent = $total ?
100 * $data['real'] / $total : 0;
424 $memory = $data['memory'];
425 $prof .= sprintf( $format,
426 substr( $fname, 0, $nameWidth ),
428 (float)( $data['real'] * 1000 ),
429 (float)( $data['real'] * 1000 ) / $calls,
432 ( $data['min_real'] * 1000.0 ),
433 ( $data['max_real'] * 1000.0 ),
437 $prof .= "\nTotal: $total\n\n";
445 public function getRawData() {
446 // This method is called before shutdown in the footer method on Skins.
447 // If some outer methods have not yet called wfProfileOut(), work around
448 // that by clearing anything in the work stack to just the "-total" entry.
449 // Collate after doing this so the results do not include profile errors.
450 if ( count( $this->workStack
) > 1 ) {
451 $oldWorkStack = $this->workStack
;
452 $this->workStack
= array( $this->workStack
[0] ); // just the "-total" one
454 $oldWorkStack = null;
456 $this->collateData();
457 // If this trick is used, then the old work stack is swapped back afterwards
458 // and collateDone is reset to false. This means that logData() will still
459 // make use of all the method data since the missing wfProfileOut() calls
460 // should be made by the time it is called.
461 if ( $oldWorkStack ) {
462 $this->workStack
= $oldWorkStack;
463 $this->collateDone
= false;
466 $total = isset( $this->collated
['-total'] )
467 ?
$this->collated
['-total']['real']
471 foreach ( $this->collated
as $fname => $data ) {
473 foreach ( $data['periods'] as $period ) {
474 $period['start'] *= 1000;
475 $period['end'] *= 1000;
476 $periods[] = $period;
480 'calls' => $data['count'],
481 'elapsed' => $data['real'] * 1000,
482 'percent' => $total ?
100 * $data['real'] / $total : 0,
483 'memory' => $data['memory'],
484 'min' => $data['min_real'] * 1000,
485 'max' => $data['max_real'] * 1000,
486 'overhead' => $data['overhead'],
487 'periods' => $periods
495 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
496 * @param int $profileCount
498 protected static function calculateOverhead( $profileCount ) {
499 wfProfileIn( '-overhead-total' );
500 for ( $i = 0; $i < $profileCount; $i++
) {
501 wfProfileIn( '-overhead-internal' );
502 wfProfileOut( '-overhead-internal' );
504 wfProfileOut( '-overhead-total' );
508 * Counts the number of profiled function calls sitting under
509 * the given point in the call graph. Not the most efficient algo.
511 * @param array $stack
515 protected function calltreeCount( $stack, $start ) {
516 $level = $stack[$start][1];
518 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
525 * Get the content type sent out to the client.
526 * Used for profilers that output instead of store data.
529 protected function getContentType() {
530 foreach ( headers_list() as $header ) {
531 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
539 * Add an entry in the debug log file
541 * @param string $s String to output
543 protected function debug( $s ) {
544 if ( function_exists( 'wfDebug' ) ) {
550 * Add an entry in the debug log group
552 * @param string $group Group to send the message to
553 * @param string $s String to output
555 protected function debugGroup( $group, $s ) {
556 if ( function_exists( 'wfDebugLog' ) ) {
557 wfDebugLog( $group, $s );