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 $mStack = array();
36 /** @var array Queue of open profile calls with start data */
37 protected $mWorkStack = array();
39 /** @var array Map of (function name => aggregate data array) */
40 protected $mCollated = array();
42 protected $mCollateDone = false;
43 /** @var bool Whether to collect the full stack trace or just aggregates */
44 protected $mCollateOnly = true;
45 /** @var array Cache of a standard broken collation entry */
46 protected $mErrorEntry;
49 * @param array $params
51 public function __construct( array $params ) {
52 parent
::__construct( $params );
54 $this->addInitialStack();
58 * Return whether this a stub profiler
62 public function isStub() {
67 * Return whether this profiler stores data
69 * @see Profiler::logData()
72 public function isPersistent() {
77 * Add the inital item in the stack.
79 protected function addInitialStack() {
80 $this->mErrorEntry
= $this->getErrorEntry();
82 $initialTime = $this->getInitialTime( 'wall' );
83 $initialCpu = $this->getInitialTime( 'cpu' );
84 if ( $initialTime !== null && $initialCpu !== null ) {
85 $this->mWorkStack
[] = array( '-total', 0, $initialTime, $initialCpu, 0 );
86 if ( $this->mCollateOnly
) {
87 $this->mWorkStack
[] = array( '-setup', 1, $initialTime, $initialCpu, 0 );
88 $this->profileOut( '-setup' );
90 $this->mStack
[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
91 $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
94 $this->profileIn( '-total' );
99 * @return array Initial collation entry
101 protected function getZeroEntry() {
113 'periods' => array(), // not filled if mCollateOnly
114 'overhead' => 0 // not filled if mCollateOnly
119 * @return array Initial collation entry for errors
121 protected function getErrorEntry() {
122 $entry = $this->getZeroEntry();
128 * Update the collation entry for a given method name
130 * @param string $name
131 * @param float $elapsedCpu
132 * @param float $elapsedReal
133 * @param int $memChange
134 * @param int $subcalls
135 * @param array|null $period Map of ('start','end','memory','subcalls')
137 protected function updateEntry(
138 $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
140 $entry =& $this->mCollated
[$name];
141 if ( !is_array( $entry ) ) {
142 $entry = $this->getZeroEntry();
143 $this->mCollated
[$name] =& $entry;
145 $entry['cpu'] +
= $elapsedCpu;
146 $entry['cpu_sq'] +
= $elapsedCpu * $elapsedCpu;
147 $entry['real'] +
= $elapsedReal;
148 $entry['real_sq'] +
= $elapsedReal * $elapsedReal;
149 $entry['memory'] +
= $memChange > 0 ?
$memChange : 0;
151 $entry['min_cpu'] = $elapsedCpu < $entry['min_cpu'] ?
$elapsedCpu : $entry['min_cpu'];
152 $entry['max_cpu'] = $elapsedCpu > $entry['max_cpu'] ?
$elapsedCpu : $entry['max_cpu'];
153 $entry['min_real'] = $elapsedReal < $entry['min_real'] ?
$elapsedReal : $entry['min_real'];
154 $entry['max_real'] = $elapsedReal > $entry['max_real'] ?
$elapsedReal : $entry['max_real'];
155 // Apply optional fields
156 $entry['overhead'] +
= $subcalls;
158 $entry['periods'][] = $period;
163 * Called by wfProfieIn()
165 * @param string $functionname
167 public function profileIn( $functionname ) {
168 global $wgDebugFunctionEntry;
170 if ( $wgDebugFunctionEntry ) {
171 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) .
172 'Entering ' . $functionname . "\n" );
175 $this->mWorkStack
[] = array(
177 count( $this->mWorkStack
),
178 $this->getTime( 'time' ),
179 $this->getTime( 'cpu' ),
185 * Called by wfProfieOut()
187 * @param string $functionname
189 public function profileOut( $functionname ) {
190 global $wgDebugFunctionEntry;
192 if ( $wgDebugFunctionEntry ) {
193 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) .
194 'Exiting ' . $functionname . "\n" );
197 $item = array_pop( $this->mWorkStack
);
198 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
200 if ( $item === null ) {
201 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
203 if ( $functionname === 'close' ) {
204 if ( $ofname !== '-total' ) {
205 $message = "Profile section ended by close(): {$ofname}";
206 $this->debugGroup( 'profileerror', $message );
207 if ( $this->mCollateOnly
) {
208 $this->mCollated
[$message] = $this->mErrorEntry
;
210 $this->mStack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
213 $functionname = $ofname;
214 } elseif ( $ofname !== $functionname ) {
215 $message = "Profiling error: in({$ofname}), out($functionname)";
216 $this->debugGroup( 'profileerror', $message );
217 if ( $this->mCollateOnly
) {
218 $this->mCollated
[$message] = $this->mErrorEntry
;
220 $this->mStack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
223 $realTime = $this->getTime( 'wall' );
224 $cpuTime = $this->getTime( 'cpu' );
225 if ( $this->mCollateOnly
) {
226 $elapsedcpu = $cpuTime - $octime;
227 $elapsedreal = $realTime - $ortime;
228 $memchange = memory_get_usage() - $omem;
229 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
231 $this->mStack
[] = array_merge( $item,
232 array( $realTime, $cpuTime, memory_get_usage() ) );
238 * Close opened profiling sections
240 public function close() {
241 while ( count( $this->mWorkStack
) ) {
242 $this->profileOut( 'close' );
247 * Log the data to some store or even the page output
249 public function logData() {
250 /* Implement in subclasses */
254 * Returns a profiling output to be stored in debug file
258 public function getOutput() {
259 global $wgDebugFunctionEntry, $wgProfileCallTree;
261 $wgDebugFunctionEntry = false; // hack
263 if ( !count( $this->mStack
) && !count( $this->mCollated
) ) {
264 return "No profiling output\n";
267 if ( $wgProfileCallTree ) {
268 return $this->getCallTree();
270 return $this->getFunctionReport();
275 * Returns a tree of function call instead of a list of functions
278 protected function getCallTree() {
279 return implode( '', array_map(
280 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
)
285 * Recursive function the format the current profiling array into a tree
287 * @param array $stack Profiling array
290 protected function remapCallTree( array $stack ) {
291 if ( count( $stack ) < 2 ) {
295 for ( $max = count( $stack ) - 1; $max > 0; ) {
296 /* Find all items under this entry */
297 $level = $stack[$max][1];
299 for ( $i = $max -1; $i >= 0; $i-- ) {
300 if ( $stack[$i][1] > $level ) {
301 $working[] = $stack[$i];
306 $working = $this->remapCallTree( array_reverse( $working ) );
308 foreach ( $working as $item ) {
309 array_push( $output, $item );
311 array_unshift( $output, $stack[$max] );
314 array_unshift( $outputs, $output );
317 foreach ( $outputs as $output ) {
318 foreach ( $output as $item ) {
326 * Callback to get a formatted line for the call tree
327 * @param array $entry
330 protected function getCallTreeLine( $entry ) {
331 list( $fname, $level, $startreal, , , $endreal ) = $entry;
332 $delta = $endreal - $startreal;
333 $space = str_repeat( ' ', $level );
334 # The ugly double sprintf is to work around a PHP bug,
335 # which has been fixed in recent releases.
336 return sprintf( "%10s %s %s\n",
337 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
343 protected function collateData() {
344 if ( $this->mCollateDone
) {
347 $this->mCollateDone
= true;
348 $this->close(); // set "-total" entry
350 if ( $this->mCollateOnly
) {
351 return; // already collated as methods exited
354 $this->mCollated
= array();
356 # Estimate profiling overhead
357 $profileCount = count( $this->mStack
);
358 self
::calculateOverhead( $profileCount );
360 # First, subtract the overhead!
361 $overheadTotal = $overheadMemory = $overheadInternal = array();
362 foreach ( $this->mStack
as $entry ) {
363 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
365 $elapsed = $entry[5] - $entry[2];
366 $memchange = $entry[7] - $entry[4];
368 if ( $fname === '-overhead-total' ) {
369 $overheadTotal[] = $elapsed;
370 $overheadMemory[] = max( 0, $memchange );
371 } elseif ( $fname === '-overhead-internal' ) {
372 $overheadInternal[] = $elapsed;
375 $overheadTotal = $overheadTotal ?
376 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
377 $overheadMemory = $overheadMemory ?
378 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
379 $overheadInternal = $overheadInternal ?
380 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
383 foreach ( $this->mStack
as $index => $entry ) {
384 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
386 $elapsedCpu = $entry[6] - $entry[3];
387 $elapsedReal = $entry[5] - $entry[2];
388 $memchange = $entry[7] - $entry[4];
389 $subcalls = $this->calltreeCount( $this->mStack
, $index );
391 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
392 # Adjust for profiling overhead (except special values with elapsed=0
394 $elapsed -= $overheadInternal;
395 $elapsed -= ( $subcalls * $overheadTotal );
396 $memchange -= ( $subcalls * $overheadMemory );
400 $period = array( 'start' => $entry[2], 'end' => $entry[5],
401 'memory' => $memchange, 'subcalls' => $subcalls );
402 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
405 $this->mCollated
['-overhead-total']['count'] = $profileCount;
406 arsort( $this->mCollated
, SORT_NUMERIC
);
410 * Returns a list of profiled functions.
414 protected function getFunctionReport() {
415 $this->collateData();
418 $nameWidth = $width - 65;
419 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
420 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
421 $prof = "\nProfiling data\n";
422 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
424 $total = isset( $this->mCollated
['-total'] )
425 ?
$this->mCollated
['-total']['real']
428 foreach ( $this->mCollated
as $fname => $data ) {
429 $calls = $data['count'];
430 $percent = $total ?
100 * $data['real'] / $total : 0;
431 $memory = $data['memory'];
432 $prof .= sprintf( $format,
433 substr( $fname, 0, $nameWidth ),
435 (float)( $data['real'] * 1000 ),
436 (float)( $data['real'] * 1000 ) / $calls,
439 ( $data['min_real'] * 1000.0 ),
440 ( $data['max_real'] * 1000.0 ),
444 $prof .= "\nTotal: $total\n\n";
452 public function getRawData() {
453 // This method is called before shutdown in the footer method on Skins.
454 // If some outer methods have not yet called wfProfileOut(), work around
455 // that by clearing anything in the work stack to just the "-total" entry.
456 // Collate after doing this so the results do not include profile errors.
457 if ( count( $this->mWorkStack
) > 1 ) {
458 $oldWorkStack = $this->mWorkStack
;
459 $this->mWorkStack
= array( $this->mWorkStack
[0] ); // just the "-total" one
461 $oldWorkStack = null;
463 $this->collateData();
464 // If this trick is used, then the old work stack is swapped back afterwards
465 // and mCollateDone is reset to false. This means that logData() will still
466 // make use of all the method data since the missing wfProfileOut() calls
467 // should be made by the time it is called.
468 if ( $oldWorkStack ) {
469 $this->mWorkStack
= $oldWorkStack;
470 $this->mCollateDone
= false;
473 $total = isset( $this->mCollated
['-total'] )
474 ?
$this->mCollated
['-total']['real']
478 foreach ( $this->mCollated
as $fname => $data ) {
480 foreach ( $data['periods'] as $period ) {
481 $period['start'] *= 1000;
482 $period['end'] *= 1000;
483 $periods[] = $period;
487 'calls' => $data['count'],
488 'elapsed' => $data['real'] * 1000,
489 'percent' => $total ?
100 * $data['real'] / $total : 0,
490 'memory' => $data['memory'],
491 'min' => $data['min_real'] * 1000,
492 'max' => $data['max_real'] * 1000,
493 'overhead' => $data['overhead'],
494 'periods' => $periods
502 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
503 * @param int $profileCount
505 protected static function calculateOverhead( $profileCount ) {
506 wfProfileIn( '-overhead-total' );
507 for ( $i = 0; $i < $profileCount; $i++
) {
508 wfProfileIn( '-overhead-internal' );
509 wfProfileOut( '-overhead-internal' );
511 wfProfileOut( '-overhead-total' );
515 * Counts the number of profiled function calls sitting under
516 * the given point in the call graph. Not the most efficient algo.
518 * @param array $stack
522 protected function calltreeCount( $stack, $start ) {
523 $level = $stack[$start][1];
525 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
532 * Get the content type sent out to the client.
533 * Used for profilers that output instead of store data.
536 protected function getContentType() {
537 foreach ( headers_list() as $header ) {
538 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {