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