Merge "API: Fix simplified continuation module skipping"
[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 $this->trxProfiler->recordFunctionCompletion( $functionname, $realTime - $ortime );
235 }
236 }
237
238 /**
239 * Close opened profiling sections
240 */
241 public function close() {
242 while ( count( $this->mWorkStack ) ) {
243 $this->profileOut( 'close' );
244 }
245 }
246
247 /**
248 * Log the data to some store or even the page output
249 */
250 public function logData() {
251 /* Implement in subclasses */
252 }
253
254 /**
255 * Returns a profiling output to be stored in debug file
256 *
257 * @return string
258 */
259 public function getOutput() {
260 global $wgDebugFunctionEntry, $wgProfileCallTree;
261
262 $wgDebugFunctionEntry = false; // hack
263
264 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
265 return "No profiling output\n";
266 }
267
268 if ( $wgProfileCallTree ) {
269 return $this->getCallTree();
270 } else {
271 return $this->getFunctionReport();
272 }
273 }
274
275 /**
276 * Returns a tree of function call instead of a list of functions
277 * @return string
278 */
279 protected function getCallTree() {
280 return implode( '', array_map(
281 array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack )
282 ) );
283 }
284
285 /**
286 * Recursive function the format the current profiling array into a tree
287 *
288 * @param array $stack Profiling array
289 * @return array
290 */
291 protected function remapCallTree( array $stack ) {
292 if ( count( $stack ) < 2 ) {
293 return $stack;
294 }
295 $outputs = array();
296 for ( $max = count( $stack ) - 1; $max > 0; ) {
297 /* Find all items under this entry */
298 $level = $stack[$max][1];
299 $working = array();
300 for ( $i = $max -1; $i >= 0; $i-- ) {
301 if ( $stack[$i][1] > $level ) {
302 $working[] = $stack[$i];
303 } else {
304 break;
305 }
306 }
307 $working = $this->remapCallTree( array_reverse( $working ) );
308 $output = array();
309 foreach ( $working as $item ) {
310 array_push( $output, $item );
311 }
312 array_unshift( $output, $stack[$max] );
313 $max = $i;
314
315 array_unshift( $outputs, $output );
316 }
317 $final = array();
318 foreach ( $outputs as $output ) {
319 foreach ( $output as $item ) {
320 $final[] = $item;
321 }
322 }
323 return $final;
324 }
325
326 /**
327 * Callback to get a formatted line for the call tree
328 * @param array $entry
329 * @return string
330 */
331 protected function getCallTreeLine( $entry ) {
332 list( $fname, $level, $startreal, , , $endreal ) = $entry;
333 $delta = $endreal - $startreal;
334 $space = str_repeat( ' ', $level );
335 # The ugly double sprintf is to work around a PHP bug,
336 # which has been fixed in recent releases.
337 return sprintf( "%10s %s %s\n",
338 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
339 }
340
341 /**
342 * Populate mCollated
343 */
344 protected function collateData() {
345 if ( $this->mCollateDone ) {
346 return;
347 }
348 $this->mCollateDone = true;
349 $this->close(); // set "-total" entry
350
351 if ( $this->mCollateOnly ) {
352 return; // already collated as methods exited
353 }
354
355 $this->mCollated = array();
356
357 # Estimate profiling overhead
358 $profileCount = count( $this->mStack );
359 self::calculateOverhead( $profileCount );
360
361 # First, subtract the overhead!
362 $overheadTotal = $overheadMemory = $overheadInternal = array();
363 foreach ( $this->mStack as $entry ) {
364 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
365 $fname = $entry[0];
366 $elapsed = $entry[5] - $entry[2];
367 $memchange = $entry[7] - $entry[4];
368
369 if ( $fname === '-overhead-total' ) {
370 $overheadTotal[] = $elapsed;
371 $overheadMemory[] = max( 0, $memchange );
372 } elseif ( $fname === '-overhead-internal' ) {
373 $overheadInternal[] = $elapsed;
374 }
375 }
376 $overheadTotal = $overheadTotal ?
377 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
378 $overheadMemory = $overheadMemory ?
379 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
380 $overheadInternal = $overheadInternal ?
381 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
382
383 # Collate
384 foreach ( $this->mStack as $index => $entry ) {
385 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
386 $fname = $entry[0];
387 $elapsedCpu = $entry[6] - $entry[3];
388 $elapsedReal = $entry[5] - $entry[2];
389 $memchange = $entry[7] - $entry[4];
390 $subcalls = $this->calltreeCount( $this->mStack, $index );
391
392 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
393 # Adjust for profiling overhead (except special values with elapsed=0
394 if ( $elapsed ) {
395 $elapsed -= $overheadInternal;
396 $elapsed -= ( $subcalls * $overheadTotal );
397 $memchange -= ( $subcalls * $overheadMemory );
398 }
399 }
400
401 $period = array( 'start' => $entry[2], 'end' => $entry[5],
402 'memory' => $memchange, 'subcalls' => $subcalls );
403 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
404 }
405
406 $this->mCollated['-overhead-total']['count'] = $profileCount;
407 arsort( $this->mCollated, SORT_NUMERIC );
408 }
409
410 /**
411 * Returns a list of profiled functions.
412 *
413 * @return string
414 */
415 protected function getFunctionReport() {
416 $this->collateData();
417
418 $width = 140;
419 $nameWidth = $width - 65;
420 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
421 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
422 $prof = "\nProfiling data\n";
423 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
424
425 $total = isset( $this->mCollated['-total'] )
426 ? $this->mCollated['-total']['real']
427 : 0;
428
429 foreach ( $this->mCollated as $fname => $data ) {
430 $calls = $data['count'];
431 $percent = $total ? 100 * $data['real'] / $total : 0;
432 $memory = $data['memory'];
433 $prof .= sprintf( $format,
434 substr( $fname, 0, $nameWidth ),
435 $calls,
436 (float)( $data['real'] * 1000 ),
437 (float)( $data['real'] * 1000 ) / $calls,
438 $percent,
439 $memory,
440 ( $data['min_real'] * 1000.0 ),
441 ( $data['max_real'] * 1000.0 ),
442 $data['overhead']
443 );
444 }
445 $prof .= "\nTotal: $total\n\n";
446
447 return $prof;
448 }
449
450 /**
451 * @return array
452 */
453 public function getRawData() {
454 // This method is called before shutdown in the footer method on Skins.
455 // If some outer methods have not yet called wfProfileOut(), work around
456 // that by clearing anything in the work stack to just the "-total" entry.
457 // Collate after doing this so the results do not include profile errors.
458 if ( count( $this->mWorkStack ) > 1 ) {
459 $oldWorkStack = $this->mWorkStack;
460 $this->mWorkStack = array( $this->mWorkStack[0] ); // just the "-total" one
461 } else {
462 $oldWorkStack = null;
463 }
464 $this->collateData();
465 // If this trick is used, then the old work stack is swapped back afterwards
466 // and mCollateDone is reset to false. This means that logData() will still
467 // make use of all the method data since the missing wfProfileOut() calls
468 // should be made by the time it is called.
469 if ( $oldWorkStack ) {
470 $this->mWorkStack = $oldWorkStack;
471 $this->mCollateDone = false;
472 }
473
474 $total = isset( $this->mCollated['-total'] )
475 ? $this->mCollated['-total']['real']
476 : 0;
477
478 $profile = array();
479 foreach ( $this->mCollated as $fname => $data ) {
480 $periods = array();
481 foreach ( $data['periods'] as $period ) {
482 $period['start'] *= 1000;
483 $period['end'] *= 1000;
484 $periods[] = $period;
485 }
486 $profile[] = array(
487 'name' => $fname,
488 'calls' => $data['count'],
489 'elapsed' => $data['real'] * 1000,
490 'percent' => $total ? 100 * $data['real'] / $total : 0,
491 'memory' => $data['memory'],
492 'min' => $data['min_real'] * 1000,
493 'max' => $data['max_real'] * 1000,
494 'overhead' => $data['overhead'],
495 'periods' => $periods
496 );
497 }
498
499 return $profile;
500 }
501
502 /**
503 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
504 * @param int $profileCount
505 */
506 protected static function calculateOverhead( $profileCount ) {
507 wfProfileIn( '-overhead-total' );
508 for ( $i = 0; $i < $profileCount; $i++ ) {
509 wfProfileIn( '-overhead-internal' );
510 wfProfileOut( '-overhead-internal' );
511 }
512 wfProfileOut( '-overhead-total' );
513 }
514
515 /**
516 * Counts the number of profiled function calls sitting under
517 * the given point in the call graph. Not the most efficient algo.
518 *
519 * @param array $stack
520 * @param int $start
521 * @return int
522 */
523 protected function calltreeCount( $stack, $start ) {
524 $level = $stack[$start][1];
525 $count = 0;
526 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
527 $count ++;
528 }
529 return $count;
530 }
531
532 /**
533 * Get the content type sent out to the client.
534 * Used for profilers that output instead of store data.
535 * @return string
536 */
537 protected function getContentType() {
538 foreach ( headers_list() as $header ) {
539 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
540 return $m[1];
541 }
542 }
543 return null;
544 }
545 }