Remove per-template profiling
[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 /**
231 * Close opened profiling sections
232 */
233 public function close() {
234 while ( count( $this->workStack ) ) {
235 $this->profileOut( 'close' );
236 }
237 }
238
239 /**
240 * Log the data to some store or even the page output
241 */
242 public function logData() {
243 /* Implement in subclasses */
244 }
245
246 /**
247 * Returns a profiling output to be stored in debug file
248 *
249 * @return string
250 */
251 public function getOutput() {
252 global $wgDebugFunctionEntry, $wgProfileCallTree;
253
254 $wgDebugFunctionEntry = false; // hack
255
256 if ( !count( $this->stack ) && !count( $this->collated ) ) {
257 return "No profiling output\n";
258 }
259
260 if ( $wgProfileCallTree ) {
261 return $this->getCallTree();
262 } else {
263 return $this->getFunctionReport();
264 }
265 }
266
267 /**
268 * Returns a tree of function call instead of a list of functions
269 * @return string
270 */
271 protected function getCallTree() {
272 return implode( '', array_map(
273 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack )
274 ) );
275 }
276
277 /**
278 * Recursive function the format the current profiling array into a tree
279 *
280 * @param array $stack Profiling array
281 * @return array
282 */
283 protected function remapCallTree( array $stack ) {
284 if ( count( $stack ) < 2 ) {
285 return $stack;
286 }
287 $outputs = array();
288 for ( $max = count( $stack ) - 1; $max > 0; ) {
289 /* Find all items under this entry */
290 $level = $stack[$max][1];
291 $working = array();
292 for ( $i = $max -1; $i >= 0; $i-- ) {
293 if ( $stack[$i][1] > $level ) {
294 $working[] = $stack[$i];
295 } else {
296 break;
297 }
298 }
299 $working = $this->remapCallTree( array_reverse( $working ) );
300 $output = array();
301 foreach ( $working as $item ) {
302 array_push( $output, $item );
303 }
304 array_unshift( $output, $stack[$max] );
305 $max = $i;
306
307 array_unshift( $outputs, $output );
308 }
309 $final = array();
310 foreach ( $outputs as $output ) {
311 foreach ( $output as $item ) {
312 $final[] = $item;
313 }
314 }
315 return $final;
316 }
317
318 /**
319 * Callback to get a formatted line for the call tree
320 * @param array $entry
321 * @return string
322 */
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 );
331 }
332
333 /**
334 * Populate collated
335 */
336 protected function collateData() {
337 if ( $this->collateDone ) {
338 return;
339 }
340 $this->collateDone = true;
341 $this->close(); // set "-total" entry
342
343 if ( $this->collateOnly ) {
344 return; // already collated as methods exited
345 }
346
347 $this->collated = array();
348
349 # Estimate profiling overhead
350 $profileCount = count( $this->stack );
351 self::calculateOverhead( $profileCount );
352
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)
357 $fname = $entry[0];
358 $elapsed = $entry[5] - $entry[2];
359 $memchange = $entry[7] - $entry[4];
360
361 if ( $fname === '-overhead-total' ) {
362 $overheadTotal[] = $elapsed;
363 $overheadMemory[] = max( 0, $memchange );
364 } elseif ( $fname === '-overhead-internal' ) {
365 $overheadInternal[] = $elapsed;
366 }
367 }
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;
374
375 # Collate
376 foreach ( $this->stack as $index => $entry ) {
377 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
378 $fname = $entry[0];
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 );
383
384 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
385 # Adjust for profiling overhead (except special values with elapsed=0
386 if ( $elapsed ) {
387 $elapsed -= $overheadInternal;
388 $elapsed -= ( $subcalls * $overheadTotal );
389 $memchange -= ( $subcalls * $overheadMemory );
390 }
391 }
392
393 $period = array( 'start' => $entry[2], 'end' => $entry[5],
394 'memory' => $memchange, 'subcalls' => $subcalls );
395 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
396 }
397
398 $this->collated['-overhead-total']['count'] = $profileCount;
399 arsort( $this->collated, SORT_NUMERIC );
400 }
401
402 /**
403 * Returns a list of profiled functions.
404 *
405 * @return string
406 */
407 protected function getFunctionReport() {
408 $this->collateData();
409
410 $width = 140;
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' );
416
417 $total = isset( $this->collated['-total'] )
418 ? $this->collated['-total']['real']
419 : 0;
420
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 ),
427 $calls,
428 (float)( $data['real'] * 1000 ),
429 (float)( $data['real'] * 1000 ) / $calls,
430 $percent,
431 $memory,
432 ( $data['min_real'] * 1000.0 ),
433 ( $data['max_real'] * 1000.0 ),
434 $data['overhead']
435 );
436 }
437 $prof .= "\nTotal: $total\n\n";
438
439 return $prof;
440 }
441
442 /**
443 * @return array
444 */
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
453 } else {
454 $oldWorkStack = null;
455 }
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;
464 }
465
466 $total = isset( $this->collated['-total'] )
467 ? $this->collated['-total']['real']
468 : 0;
469
470 $profile = array();
471 foreach ( $this->collated as $fname => $data ) {
472 $periods = array();
473 foreach ( $data['periods'] as $period ) {
474 $period['start'] *= 1000;
475 $period['end'] *= 1000;
476 $periods[] = $period;
477 }
478 $profile[] = array(
479 'name' => $fname,
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
488 );
489 }
490
491 return $profile;
492 }
493
494 /**
495 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
496 * @param int $profileCount
497 */
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' );
503 }
504 wfProfileOut( '-overhead-total' );
505 }
506
507 /**
508 * Counts the number of profiled function calls sitting under
509 * the given point in the call graph. Not the most efficient algo.
510 *
511 * @param array $stack
512 * @param int $start
513 * @return int
514 */
515 protected function calltreeCount( $stack, $start ) {
516 $level = $stack[$start][1];
517 $count = 0;
518 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
519 $count ++;
520 }
521 return $count;
522 }
523
524 /**
525 * Get the content type sent out to the client.
526 * Used for profilers that output instead of store data.
527 * @return string
528 */
529 protected function getContentType() {
530 foreach ( headers_list() as $header ) {
531 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
532 return $m[1];
533 }
534 }
535 return null;
536 }
537
538 /**
539 * Add an entry in the debug log file
540 *
541 * @param string $s String to output
542 */
543 protected function debug( $s ) {
544 if ( function_exists( 'wfDebug' ) ) {
545 wfDebug( $s );
546 }
547 }
548
549 /**
550 * Add an entry in the debug log group
551 *
552 * @param string $group Group to send the message to
553 * @param string $s String to output
554 */
555 protected function debugGroup( $group, $s ) {
556 if ( function_exists( 'wfDebugLog' ) ) {
557 wfDebugLog( $group, $s );
558 }
559 }
560 }