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 * Return whether this profiler stores data
72 * @see Profiler::logData()
75 public function isPersistent() {
80 * Add the inital item in the stack.
82 protected function addInitialStack() {
83 $this->errorEntry
= $this->getErrorEntry();
85 $initialTime = $this->getInitialTime( 'wall' );
86 $initialCpu = $this->getInitialTime( 'cpu' );
87 if ( $initialTime !== null && $initialCpu !== null ) {
88 $this->workStack
[] = array( '-total', 0, $initialTime, $initialCpu, 0 );
89 if ( $this->collateOnly
) {
90 $this->workStack
[] = array( '-setup', 1, $initialTime, $initialCpu, 0 );
91 $this->profileOut( '-setup' );
93 $this->stack
[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
94 $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
97 $this->profileIn( '-total' );
102 * @return array Initial collation entry
104 protected function getZeroEntry() {
116 'periods' => array(), // not filled if collateOnly
117 'overhead' => 0 // not filled if collateOnly
122 * @return array Initial collation entry for errors
124 protected function getErrorEntry() {
125 $entry = $this->getZeroEntry();
131 * Update the collation entry for a given method name
133 * @param string $name
134 * @param float $elapsedCpu
135 * @param float $elapsedReal
136 * @param int $memChange
137 * @param int $subcalls
138 * @param array|null $period Map of ('start','end','memory','subcalls')
140 protected function updateEntry(
141 $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
143 $entry =& $this->collated
[$name];
144 if ( !is_array( $entry ) ) {
145 $entry = $this->getZeroEntry();
146 $this->collated
[$name] =& $entry;
148 $entry['cpu'] +
= $elapsedCpu;
149 $entry['cpu_sq'] +
= $elapsedCpu * $elapsedCpu;
150 $entry['real'] +
= $elapsedReal;
151 $entry['real_sq'] +
= $elapsedReal * $elapsedReal;
152 $entry['memory'] +
= $memChange > 0 ?
$memChange : 0;
154 $entry['min_cpu'] = $elapsedCpu < $entry['min_cpu'] ?
$elapsedCpu : $entry['min_cpu'];
155 $entry['max_cpu'] = $elapsedCpu > $entry['max_cpu'] ?
$elapsedCpu : $entry['max_cpu'];
156 $entry['min_real'] = $elapsedReal < $entry['min_real'] ?
$elapsedReal : $entry['min_real'];
157 $entry['max_real'] = $elapsedReal > $entry['max_real'] ?
$elapsedReal : $entry['max_real'];
158 // Apply optional fields
159 $entry['overhead'] +
= $subcalls;
161 $entry['periods'][] = $period;
166 * Called by wfProfieIn()
168 * @param string $functionname
170 public function profileIn( $functionname ) {
171 global $wgDebugFunctionEntry;
173 if ( $wgDebugFunctionEntry ) {
174 $this->debug( str_repeat( ' ', count( $this->workStack
) ) .
175 'Entering ' . $functionname . "\n" );
178 $this->workStack
[] = array(
180 count( $this->workStack
),
181 $this->getTime( 'time' ),
182 $this->getTime( 'cpu' ),
188 * Called by wfProfieOut()
190 * @param string $functionname
192 public function profileOut( $functionname ) {
193 global $wgDebugFunctionEntry;
195 if ( $wgDebugFunctionEntry ) {
196 $this->debug( str_repeat( ' ', count( $this->workStack
) - 1 ) .
197 'Exiting ' . $functionname . "\n" );
200 $item = array_pop( $this->workStack
);
201 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
203 if ( $item === null ) {
204 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
206 if ( $functionname === 'close' ) {
207 if ( $ofname !== '-total' ) {
208 $message = "Profile section ended by close(): {$ofname}";
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 $functionname = $ofname;
217 } elseif ( $ofname !== $functionname ) {
218 $message = "Profiling error: in({$ofname}), out($functionname)";
219 $this->debugGroup( 'profileerror', $message );
220 if ( $this->collateOnly
) {
221 $this->collated
[$message] = $this->errorEntry
;
223 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
226 $realTime = $this->getTime( 'wall' );
227 $cpuTime = $this->getTime( 'cpu' );
228 if ( $this->collateOnly
) {
229 $elapsedcpu = $cpuTime - $octime;
230 $elapsedreal = $realTime - $ortime;
231 $memchange = memory_get_usage() - $omem;
232 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
234 $this->stack
[] = array_merge( $item,
235 array( $realTime, $cpuTime, memory_get_usage() ) );
241 * Close opened profiling sections
243 public function close() {
244 while ( count( $this->workStack
) ) {
245 $this->profileOut( 'close' );
250 * Log the data to some store or even the page output
252 public function logData() {
253 /* Implement in subclasses */
257 * Returns a profiling output to be stored in debug file
261 public function getOutput() {
262 global $wgDebugFunctionEntry, $wgProfileCallTree;
264 $wgDebugFunctionEntry = false; // hack
266 if ( !count( $this->stack
) && !count( $this->collated
) ) {
267 return "No profiling output\n";
270 if ( $wgProfileCallTree ) {
271 return $this->getCallTree();
273 return $this->getFunctionReport();
278 * Returns a tree of function call instead of a list of functions
281 protected function getCallTree() {
282 return implode( '', array_map(
283 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack
)
288 * Recursive function the format the current profiling array into a tree
290 * @param array $stack Profiling array
293 protected function remapCallTree( array $stack ) {
294 if ( count( $stack ) < 2 ) {
298 for ( $max = count( $stack ) - 1; $max > 0; ) {
299 /* Find all items under this entry */
300 $level = $stack[$max][1];
302 for ( $i = $max -1; $i >= 0; $i-- ) {
303 if ( $stack[$i][1] > $level ) {
304 $working[] = $stack[$i];
309 $working = $this->remapCallTree( array_reverse( $working ) );
311 foreach ( $working as $item ) {
312 array_push( $output, $item );
314 array_unshift( $output, $stack[$max] );
317 array_unshift( $outputs, $output );
320 foreach ( $outputs as $output ) {
321 foreach ( $output as $item ) {
329 * Callback to get a formatted line for the call tree
330 * @param array $entry
333 protected function getCallTreeLine( $entry ) {
334 list( $fname, $level, $startreal, , , $endreal ) = $entry;
335 $delta = $endreal - $startreal;
336 $space = str_repeat( ' ', $level );
337 # The ugly double sprintf is to work around a PHP bug,
338 # which has been fixed in recent releases.
339 return sprintf( "%10s %s %s\n",
340 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
346 protected function collateData() {
347 if ( $this->collateDone
) {
350 $this->collateDone
= true;
351 $this->close(); // set "-total" entry
353 if ( $this->collateOnly
) {
354 return; // already collated as methods exited
357 $this->collated
= array();
359 # Estimate profiling overhead
360 $profileCount = count( $this->stack
);
361 self
::calculateOverhead( $profileCount );
363 # First, subtract the overhead!
364 $overheadTotal = $overheadMemory = $overheadInternal = array();
365 foreach ( $this->stack
as $entry ) {
366 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
368 $elapsed = $entry[5] - $entry[2];
369 $memchange = $entry[7] - $entry[4];
371 if ( $fname === '-overhead-total' ) {
372 $overheadTotal[] = $elapsed;
373 $overheadMemory[] = max( 0, $memchange );
374 } elseif ( $fname === '-overhead-internal' ) {
375 $overheadInternal[] = $elapsed;
378 $overheadTotal = $overheadTotal ?
379 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
380 $overheadMemory = $overheadMemory ?
381 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
382 $overheadInternal = $overheadInternal ?
383 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
386 foreach ( $this->stack
as $index => $entry ) {
387 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
389 $elapsedCpu = $entry[6] - $entry[3];
390 $elapsedReal = $entry[5] - $entry[2];
391 $memchange = $entry[7] - $entry[4];
392 $subcalls = $this->calltreeCount( $this->stack
, $index );
394 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
395 # Adjust for profiling overhead (except special values with elapsed=0
397 $elapsed -= $overheadInternal;
398 $elapsed -= ( $subcalls * $overheadTotal );
399 $memchange -= ( $subcalls * $overheadMemory );
403 $period = array( 'start' => $entry[2], 'end' => $entry[5],
404 'memory' => $memchange, 'subcalls' => $subcalls );
405 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
408 $this->collated
['-overhead-total']['count'] = $profileCount;
409 arsort( $this->collated
, SORT_NUMERIC
);
413 * Returns a list of profiled functions.
417 protected function getFunctionReport() {
418 $this->collateData();
421 $nameWidth = $width - 65;
422 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
423 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
424 $prof = "\nProfiling data\n";
425 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
427 $total = isset( $this->collated
['-total'] )
428 ?
$this->collated
['-total']['real']
431 foreach ( $this->collated
as $fname => $data ) {
432 $calls = $data['count'];
433 $percent = $total ?
100 * $data['real'] / $total : 0;
434 $memory = $data['memory'];
435 $prof .= sprintf( $format,
436 substr( $fname, 0, $nameWidth ),
438 (float)( $data['real'] * 1000 ),
439 (float)( $data['real'] * 1000 ) / $calls,
442 ( $data['min_real'] * 1000.0 ),
443 ( $data['max_real'] * 1000.0 ),
447 $prof .= "\nTotal: $total\n\n";
455 public function getRawData() {
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 $total = isset( $this->collated
['-total'] )
477 ?
$this->collated
['-total']['real']
481 foreach ( $this->collated
as $fname => $data ) {
483 foreach ( $data['periods'] as $period ) {
484 $period['start'] *= 1000;
485 $period['end'] *= 1000;
486 $periods[] = $period;
490 'calls' => $data['count'],
491 'elapsed' => $data['real'] * 1000,
492 'percent' => $total ?
100 * $data['real'] / $total : 0,
493 'memory' => $data['memory'],
494 'min' => $data['min_real'] * 1000,
495 'max' => $data['max_real'] * 1000,
496 'overhead' => $data['overhead'],
497 'periods' => $periods
505 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
506 * @param int $profileCount
508 protected static function calculateOverhead( $profileCount ) {
509 wfProfileIn( '-overhead-total' );
510 for ( $i = 0; $i < $profileCount; $i++
) {
511 wfProfileIn( '-overhead-internal' );
512 wfProfileOut( '-overhead-internal' );
514 wfProfileOut( '-overhead-total' );
518 * Counts the number of profiled function calls sitting under
519 * the given point in the call graph. Not the most efficient algo.
521 * @param array $stack
525 protected function calltreeCount( $stack, $start ) {
526 $level = $stack[$start][1];
528 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
535 * Get the content type sent out to the client.
536 * Used for profilers that output instead of store data.
539 protected function getContentType() {
540 foreach ( headers_list() as $header ) {
541 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
549 * Add an entry in the debug log file
551 * @param string $s String to output
553 protected function debug( $s ) {
554 if ( function_exists( 'wfDebug' ) ) {
560 * Add an entry in the debug log group
562 * @param string $group Group to send the message to
563 * @param string $s String to output
565 protected function debugGroup( $group, $s ) {
566 if ( function_exists( 'wfDebugLog' ) ) {
567 wfDebugLog( $group, $s );