Profiler: Move debug(Group)() to ProfilerStandard, not used elsewhere
[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 $mStack = array();
36 /** @var array Queue of open profile calls with start data */
37 protected $mWorkStack = array();
38
39 /** @var array Map of (function name => aggregate data array) */
40 protected $mCollated = array();
41 /** @var bool */
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;
47
48 /**
49 * @param array $params
50 */
51 public function __construct( array $params ) {
52 parent::__construct( $params );
53
54 $this->addInitialStack();
55 }
56
57 /**
58 * Return whether this a stub profiler
59 *
60 * @return bool
61 */
62 public function isStub() {
63 return false;
64 }
65
66 /**
67 * Return whether this profiler stores data
68 *
69 * @see Profiler::logData()
70 * @return bool
71 */
72 public function isPersistent() {
73 return false;
74 }
75
76 /**
77 * Add the inital item in the stack.
78 */
79 protected function addInitialStack() {
80 $this->mErrorEntry = $this->getErrorEntry();
81
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' );
89 } else {
90 $this->mStack[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
91 $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
92 }
93 } else {
94 $this->profileIn( '-total' );
95 }
96 }
97
98 /**
99 * @return array Initial collation entry
100 */
101 protected function getZeroEntry() {
102 return array(
103 'cpu' => 0.0,
104 'cpu_sq' => 0.0,
105 'real' => 0.0,
106 'real_sq' => 0.0,
107 'memory' => 0,
108 'count' => 0,
109 'min_cpu' => 0.0,
110 'max_cpu' => 0.0,
111 'min_real' => 0.0,
112 'max_real' => 0.0,
113 'periods' => array(), // not filled if mCollateOnly
114 'overhead' => 0 // not filled if mCollateOnly
115 );
116 }
117
118 /**
119 * @return array Initial collation entry for errors
120 */
121 protected function getErrorEntry() {
122 $entry = $this->getZeroEntry();
123 $entry['count'] = 1;
124 return $entry;
125 }
126
127 /**
128 * Update the collation entry for a given method name
129 *
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')
136 */
137 protected function updateEntry(
138 $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
139 ) {
140 $entry =& $this->mCollated[$name];
141 if ( !is_array( $entry ) ) {
142 $entry = $this->getZeroEntry();
143 $this->mCollated[$name] =& $entry;
144 }
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;
150 $entry['count']++;
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;
157 if ( $period ) {
158 $entry['periods'][] = $period;
159 }
160 }
161
162 /**
163 * Called by wfProfieIn()
164 *
165 * @param string $functionname
166 */
167 public function profileIn( $functionname ) {
168 global $wgDebugFunctionEntry;
169
170 if ( $wgDebugFunctionEntry ) {
171 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) .
172 'Entering ' . $functionname . "\n" );
173 }
174
175 $this->mWorkStack[] = array(
176 $functionname,
177 count( $this->mWorkStack ),
178 $this->getTime( 'time' ),
179 $this->getTime( 'cpu' ),
180 memory_get_usage()
181 );
182 }
183
184 /**
185 * Called by wfProfieOut()
186 *
187 * @param string $functionname
188 */
189 public function profileOut( $functionname ) {
190 global $wgDebugFunctionEntry;
191
192 if ( $wgDebugFunctionEntry ) {
193 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) .
194 'Exiting ' . $functionname . "\n" );
195 }
196
197 $item = array_pop( $this->mWorkStack );
198 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
199
200 if ( $item === null ) {
201 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
202 } else {
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;
209 } else {
210 $this->mStack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
211 }
212 }
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;
219 } else {
220 $this->mStack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
221 }
222 }
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 );
230 } else {
231 $this->mStack[] = array_merge( $item,
232 array( $realTime, $cpuTime, memory_get_usage() ) );
233 }
234 }
235 }
236
237 /**
238 * Close opened profiling sections
239 */
240 public function close() {
241 while ( count( $this->mWorkStack ) ) {
242 $this->profileOut( 'close' );
243 }
244 }
245
246 /**
247 * Log the data to some store or even the page output
248 */
249 public function logData() {
250 /* Implement in subclasses */
251 }
252
253 /**
254 * Returns a profiling output to be stored in debug file
255 *
256 * @return string
257 */
258 public function getOutput() {
259 global $wgDebugFunctionEntry, $wgProfileCallTree;
260
261 $wgDebugFunctionEntry = false; // hack
262
263 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
264 return "No profiling output\n";
265 }
266
267 if ( $wgProfileCallTree ) {
268 return $this->getCallTree();
269 } else {
270 return $this->getFunctionReport();
271 }
272 }
273
274 /**
275 * Returns a tree of function call instead of a list of functions
276 * @return string
277 */
278 protected function getCallTree() {
279 return implode( '', array_map(
280 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack )
281 ) );
282 }
283
284 /**
285 * Recursive function the format the current profiling array into a tree
286 *
287 * @param array $stack Profiling array
288 * @return array
289 */
290 protected function remapCallTree( array $stack ) {
291 if ( count( $stack ) < 2 ) {
292 return $stack;
293 }
294 $outputs = array();
295 for ( $max = count( $stack ) - 1; $max > 0; ) {
296 /* Find all items under this entry */
297 $level = $stack[$max][1];
298 $working = array();
299 for ( $i = $max -1; $i >= 0; $i-- ) {
300 if ( $stack[$i][1] > $level ) {
301 $working[] = $stack[$i];
302 } else {
303 break;
304 }
305 }
306 $working = $this->remapCallTree( array_reverse( $working ) );
307 $output = array();
308 foreach ( $working as $item ) {
309 array_push( $output, $item );
310 }
311 array_unshift( $output, $stack[$max] );
312 $max = $i;
313
314 array_unshift( $outputs, $output );
315 }
316 $final = array();
317 foreach ( $outputs as $output ) {
318 foreach ( $output as $item ) {
319 $final[] = $item;
320 }
321 }
322 return $final;
323 }
324
325 /**
326 * Callback to get a formatted line for the call tree
327 * @param array $entry
328 * @return string
329 */
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 );
338 }
339
340 /**
341 * Populate mCollated
342 */
343 protected function collateData() {
344 if ( $this->mCollateDone ) {
345 return;
346 }
347 $this->mCollateDone = true;
348 $this->close(); // set "-total" entry
349
350 if ( $this->mCollateOnly ) {
351 return; // already collated as methods exited
352 }
353
354 $this->mCollated = array();
355
356 # Estimate profiling overhead
357 $profileCount = count( $this->mStack );
358 self::calculateOverhead( $profileCount );
359
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)
364 $fname = $entry[0];
365 $elapsed = $entry[5] - $entry[2];
366 $memchange = $entry[7] - $entry[4];
367
368 if ( $fname === '-overhead-total' ) {
369 $overheadTotal[] = $elapsed;
370 $overheadMemory[] = max( 0, $memchange );
371 } elseif ( $fname === '-overhead-internal' ) {
372 $overheadInternal[] = $elapsed;
373 }
374 }
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;
381
382 # Collate
383 foreach ( $this->mStack as $index => $entry ) {
384 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
385 $fname = $entry[0];
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 );
390
391 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
392 # Adjust for profiling overhead (except special values with elapsed=0
393 if ( $elapsed ) {
394 $elapsed -= $overheadInternal;
395 $elapsed -= ( $subcalls * $overheadTotal );
396 $memchange -= ( $subcalls * $overheadMemory );
397 }
398 }
399
400 $period = array( 'start' => $entry[2], 'end' => $entry[5],
401 'memory' => $memchange, 'subcalls' => $subcalls );
402 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
403 }
404
405 $this->mCollated['-overhead-total']['count'] = $profileCount;
406 arsort( $this->mCollated, SORT_NUMERIC );
407 }
408
409 /**
410 * Returns a list of profiled functions.
411 *
412 * @return string
413 */
414 protected function getFunctionReport() {
415 $this->collateData();
416
417 $width = 140;
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' );
423
424 $total = isset( $this->mCollated['-total'] )
425 ? $this->mCollated['-total']['real']
426 : 0;
427
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 ),
434 $calls,
435 (float)( $data['real'] * 1000 ),
436 (float)( $data['real'] * 1000 ) / $calls,
437 $percent,
438 $memory,
439 ( $data['min_real'] * 1000.0 ),
440 ( $data['max_real'] * 1000.0 ),
441 $data['overhead']
442 );
443 }
444 $prof .= "\nTotal: $total\n\n";
445
446 return $prof;
447 }
448
449 /**
450 * @return array
451 */
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
460 } else {
461 $oldWorkStack = null;
462 }
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;
471 }
472
473 $total = isset( $this->mCollated['-total'] )
474 ? $this->mCollated['-total']['real']
475 : 0;
476
477 $profile = array();
478 foreach ( $this->mCollated as $fname => $data ) {
479 $periods = array();
480 foreach ( $data['periods'] as $period ) {
481 $period['start'] *= 1000;
482 $period['end'] *= 1000;
483 $periods[] = $period;
484 }
485 $profile[] = array(
486 'name' => $fname,
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
495 );
496 }
497
498 return $profile;
499 }
500
501 /**
502 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
503 * @param int $profileCount
504 */
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' );
510 }
511 wfProfileOut( '-overhead-total' );
512 }
513
514 /**
515 * Counts the number of profiled function calls sitting under
516 * the given point in the call graph. Not the most efficient algo.
517 *
518 * @param array $stack
519 * @param int $start
520 * @return int
521 */
522 protected function calltreeCount( $stack, $start ) {
523 $level = $stack[$start][1];
524 $count = 0;
525 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
526 $count ++;
527 }
528 return $count;
529 }
530
531 /**
532 * Get the content type sent out to the client.
533 * Used for profilers that output instead of store data.
534 * @return string
535 */
536 protected function getContentType() {
537 foreach ( headers_list() as $header ) {
538 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
539 return $m[1];
540 }
541 }
542 return null;
543 }
544
545 /**
546 * Add an entry in the debug log file
547 *
548 * @param string $s String to output
549 */
550 protected function debug( $s ) {
551 if ( function_exists( 'wfDebug' ) ) {
552 wfDebug( $s );
553 }
554 }
555
556 /**
557 * Add an entry in the debug log group
558 *
559 * @param string $group Group to send the message to
560 * @param string $s String to output
561 */
562 protected function debugGroup( $group, $s ) {
563 if ( function_exists( 'wfDebugLog' ) ) {
564 wfDebugLog( $group, $s );
565 }
566 }
567 }