c732b8d7a6cea112b7b5fbcfa208e12f26077ecf
[lhc/web/wiklou.git] / includes / profiler / Profiler.php
1 <?php
2 /**
3 * Base class and functions 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 * This file is only included if profiling is enabled
23 */
24
25 /**
26 * @defgroup Profiler Profiler
27 */
28
29 /**
30 * Begin profiling of a function
31 * @param string $functionname name of the function we will profile
32 */
33 function wfProfileIn( $functionname ) {
34 global $wgProfiler;
35 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
36 Profiler::instance()->profileIn( $functionname );
37 }
38 }
39
40 /**
41 * Stop profiling of a function
42 * @param string $functionname name of the function we have profiled
43 */
44 function wfProfileOut( $functionname = 'missing' ) {
45 global $wgProfiler;
46 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
47 Profiler::instance()->profileOut( $functionname );
48 }
49 }
50
51 /**
52 * @ingroup Profiler
53 * @todo document
54 */
55 class Profiler {
56 protected $mStack = array(), $mWorkStack = array (), $mCollated = array (),
57 $mCalls = array (), $mTotals = array ();
58 protected $mTimeMetric = 'wall';
59 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
60 private static $__instance = null;
61
62 function __construct( $params ) {
63 if ( isset( $params['timeMetric'] ) ) {
64 $this->mTimeMetric = $params['timeMetric'];
65 }
66 if ( isset( $params['profileID'] ) ) {
67 $this->mProfileID = $params['profileID'];
68 }
69
70 $this->addInitialStack();
71 }
72
73 /**
74 * Singleton
75 * @return Profiler
76 */
77 public static function instance() {
78 if( is_null( self::$__instance ) ) {
79 global $wgProfiler;
80 if( is_array( $wgProfiler ) ) {
81 if( !isset( $wgProfiler['class'] ) ) {
82 wfDebug( __METHOD__ . " called without \$wgProfiler['class']"
83 . " set, falling back to ProfilerStub for safety\n" );
84 $class = 'ProfilerStub';
85 } else {
86 $class = $wgProfiler['class'];
87 }
88 self::$__instance = new $class( $wgProfiler );
89 } elseif( $wgProfiler instanceof Profiler ) {
90 self::$__instance = $wgProfiler; // back-compat
91 } else {
92 wfDebug( __METHOD__ . ' called with bogus $wgProfiler setting,'
93 . " falling back to ProfilerStub for safety\n" );
94 self::$__instance = new ProfilerStub( $wgProfiler );
95 }
96 }
97 return self::$__instance;
98 }
99
100 /**
101 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
102 * @param $p Profiler object
103 */
104 public static function setInstance( Profiler $p ) {
105 self::$__instance = $p;
106 }
107
108 /**
109 * Return whether this a stub profiler
110 *
111 * @return Boolean
112 */
113 public function isStub() {
114 return false;
115 }
116
117 /**
118 * Return whether this profiler stores data
119 *
120 * @see Profiler::logData()
121 * @return Boolean
122 */
123 public function isPersistent() {
124 return true;
125 }
126
127 public function setProfileID( $id ) {
128 $this->mProfileID = $id;
129 }
130
131 public function getProfileID() {
132 if ( $this->mProfileID === false ) {
133 return wfWikiID();
134 } else {
135 return $this->mProfileID;
136 }
137 }
138
139 /**
140 * Add the inital item in the stack.
141 */
142 protected function addInitialStack() {
143 // Push an entry for the pre-profile setup time onto the stack
144 $initial = $this->getInitialTime();
145 if ( $initial !== null ) {
146 $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
147 $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
148 } else {
149 $this->profileIn( '-total' );
150 }
151 }
152
153 /**
154 * Called by wfProfieIn()
155 *
156 * @param $functionname String
157 */
158 public function profileIn( $functionname ) {
159 global $wgDebugFunctionEntry;
160 if( $wgDebugFunctionEntry ) {
161 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
162 }
163
164 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
165 }
166
167 /**
168 * Called by wfProfieOut()
169 *
170 * @param $functionname String
171 */
172 public function profileOut( $functionname ) {
173 global $wgDebugFunctionEntry;
174 $memory = memory_get_usage();
175 $time = $this->getTime();
176
177 if( $wgDebugFunctionEntry ) {
178 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
179 }
180
181 $bit = array_pop( $this->mWorkStack );
182
183 if ( !$bit ) {
184 $this->debug( "Profiling error, !\$bit: $functionname\n" );
185 } else {
186 //if( $wgDebugProfiling ) {
187 if( $functionname == 'close' ) {
188 $message = "Profile section ended by close(): {$bit[0]}";
189 $this->debug( "$message\n" );
190 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
191 }
192 elseif( $bit[0] != $functionname ) {
193 $message = "Profiling error: in({$bit[0]}), out($functionname)";
194 $this->debug( "$message\n" );
195 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
196 }
197 //}
198 $bit[] = $time;
199 $bit[] = $memory;
200 $this->mStack[] = $bit;
201 }
202 }
203
204 /**
205 * Close opened profiling sections
206 */
207 public function close() {
208 while( count( $this->mWorkStack ) ) {
209 $this->profileOut( 'close' );
210 }
211 }
212
213 /**
214 * Mark this call as templated or not
215 *
216 * @param $t Boolean
217 */
218 function setTemplated( $t ) {
219 $this->mTemplated = $t;
220 }
221
222 /**
223 * Returns a profiling output to be stored in debug file
224 *
225 * @return String
226 */
227 public function getOutput() {
228 global $wgDebugFunctionEntry, $wgProfileCallTree;
229 $wgDebugFunctionEntry = false;
230
231 if( !count( $this->mStack ) && !count( $this->mCollated ) ) {
232 return "No profiling output\n";
233 }
234
235 if( $wgProfileCallTree ) {
236 return $this->getCallTree();
237 } else {
238 return $this->getFunctionReport();
239 }
240 }
241
242 /**
243 * Returns a tree of function call instead of a list of functions
244 * @return string
245 */
246 function getCallTree() {
247 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
248 }
249
250 /**
251 * Recursive function the format the current profiling array into a tree
252 *
253 * @param array $stack profiling array
254 * @return array
255 */
256 function remapCallTree( $stack ) {
257 if( count( $stack ) < 2 ) {
258 return $stack;
259 }
260 $outputs = array ();
261 for( $max = count( $stack ) - 1; $max > 0; ) {
262 /* Find all items under this entry */
263 $level = $stack[$max][1];
264 $working = array ();
265 for( $i = $max -1; $i >= 0; $i-- ) {
266 if( $stack[$i][1] > $level ) {
267 $working[] = $stack[$i];
268 } else {
269 break;
270 }
271 }
272 $working = $this->remapCallTree( array_reverse( $working ) );
273 $output = array();
274 foreach( $working as $item ) {
275 array_push( $output, $item );
276 }
277 array_unshift( $output, $stack[$max] );
278 $max = $i;
279
280 array_unshift( $outputs, $output );
281 }
282 $final = array();
283 foreach( $outputs as $output ) {
284 foreach( $output as $item ) {
285 $final[] = $item;
286 }
287 }
288 return $final;
289 }
290
291 /**
292 * Callback to get a formatted line for the call tree
293 * @return string
294 */
295 function getCallTreeLine( $entry ) {
296 list( $fname, $level, $start, /* $x */, $end ) = $entry;
297 $delta = $end - $start;
298 $space = str_repeat( ' ', $level );
299 # The ugly double sprintf is to work around a PHP bug,
300 # which has been fixed in recent releases.
301 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
302 }
303
304 /**
305 * Get the initial time of the request, based either on $wgRequestTime or
306 * $wgRUstart. Will return null if not able to find data.
307 *
308 * @param string|false $metric metric to use, with the following possibilities:
309 * - user: User CPU time (without system calls)
310 * - cpu: Total CPU time (user and system calls)
311 * - wall (or any other string): elapsed time
312 * - false (default): will fall back to default metric
313 * @return float|null
314 */
315 function getTime( $metric = false ) {
316 if ( $metric === false ) {
317 $metric = $this->mTimeMetric;
318 }
319
320 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
321 if ( !function_exists( 'getrusage' ) ) {
322 return 0;
323 }
324 $ru = getrusage();
325 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
326 if ( $metric === 'cpu' ) {
327 # This is the time of system calls, added to the user time
328 # it gives the total CPU time
329 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
330 }
331 return $time;
332 } else {
333 return microtime( true );
334 }
335 }
336
337 /**
338 * Get the initial time of the request, based either on $wgRequestTime or
339 * $wgRUstart. Will return null if not able to find data.
340 *
341 * @param string|false $metric metric to use, with the following possibilities:
342 * - user: User CPU time (without system calls)
343 * - cpu: Total CPU time (user and system calls)
344 * - wall (or any other string): elapsed time
345 * - false (default): will fall back to default metric
346 * @return float|null
347 */
348 protected function getInitialTime( $metric = false ) {
349 global $wgRequestTime, $wgRUstart;
350
351 if ( $metric === false ) {
352 $metric = $this->mTimeMetric;
353 }
354
355 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
356 if ( !count( $wgRUstart ) ) {
357 return null;
358 }
359
360 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
361 if ( $metric === 'cpu' ) {
362 # This is the time of system calls, added to the user time
363 # it gives the total CPU time
364 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
365 }
366 return $time;
367 } else {
368 if ( empty( $wgRequestTime ) ) {
369 return null;
370 } else {
371 return $wgRequestTime;
372 }
373 }
374 }
375
376 protected function collateData() {
377 if ( $this->mCollateDone ) {
378 return;
379 }
380 $this->mCollateDone = true;
381
382 $this->close();
383
384 $this->mCollated = array();
385 $this->mCalls = array();
386 $this->mMemory = array();
387
388 # Estimate profiling overhead
389 $profileCount = count( $this->mStack );
390 self::calculateOverhead( $profileCount );
391
392 # First, subtract the overhead!
393 $overheadTotal = $overheadMemory = $overheadInternal = array();
394 foreach( $this->mStack as $entry ) {
395 $fname = $entry[0];
396 $start = $entry[2];
397 $end = $entry[4];
398 $elapsed = $end - $start;
399 $memory = $entry[5] - $entry[3];
400
401 if( $fname == '-overhead-total' ) {
402 $overheadTotal[] = $elapsed;
403 $overheadMemory[] = $memory;
404 }
405 elseif( $fname == '-overhead-internal' ) {
406 $overheadInternal[] = $elapsed;
407 }
408 }
409 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
410 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
411 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
412
413 # Collate
414 foreach( $this->mStack as $index => $entry ) {
415 $fname = $entry[0];
416 $start = $entry[2];
417 $end = $entry[4];
418 $elapsed = $end - $start;
419
420 $memory = $entry[5] - $entry[3];
421 $subcalls = $this->calltreeCount( $this->mStack, $index );
422
423 if( !preg_match( '/^-overhead/', $fname ) ) {
424 # Adjust for profiling overhead (except special values with elapsed=0
425 if( $elapsed ) {
426 $elapsed -= $overheadInternal;
427 $elapsed -= ($subcalls * $overheadTotal);
428 $memory -= ($subcalls * $overheadMemory);
429 }
430 }
431
432 if( !array_key_exists( $fname, $this->mCollated ) ) {
433 $this->mCollated[$fname] = 0;
434 $this->mCalls[$fname] = 0;
435 $this->mMemory[$fname] = 0;
436 $this->mMin[$fname] = 1 << 24;
437 $this->mMax[$fname] = 0;
438 $this->mOverhead[$fname] = 0;
439 }
440
441 $this->mCollated[$fname] += $elapsed;
442 $this->mCalls[$fname]++;
443 $this->mMemory[$fname] += $memory;
444 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
445 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
446 $this->mOverhead[$fname] += $subcalls;
447 }
448
449 $this->mCalls['-overhead-total'] = $profileCount;
450 arsort( $this->mCollated, SORT_NUMERIC );
451 }
452
453 /**
454 * Returns a list of profiled functions.
455 *
456 * @return string
457 */
458 function getFunctionReport() {
459 $this->collateData();
460
461 $width = 140;
462 $nameWidth = $width - 65;
463 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
464 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
465 $prof = "\nProfiling data\n";
466 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
467
468 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
469
470 foreach( $this->mCollated as $fname => $elapsed ) {
471 $calls = $this->mCalls[$fname];
472 $percent = $total ? 100. * $elapsed / $total : 0;
473 $memory = $this->mMemory[$fname];
474 $prof .= sprintf( $format, substr( $fname, 0, $nameWidth ), $calls, (float) ($elapsed * 1000), (float) ($elapsed * 1000) / $calls, $percent, $memory, ( $this->mMin[$fname] * 1000.0 ), ( $this->mMax[$fname] * 1000.0 ), $this->mOverhead[$fname] );
475 }
476 $prof .= "\nTotal: $total\n\n";
477
478 return $prof;
479 }
480
481 /**
482 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
483 */
484 protected static function calculateOverhead( $profileCount ) {
485 wfProfileIn( '-overhead-total' );
486 for( $i = 0; $i < $profileCount; $i++ ) {
487 wfProfileIn( '-overhead-internal' );
488 wfProfileOut( '-overhead-internal' );
489 }
490 wfProfileOut( '-overhead-total' );
491 }
492
493 /**
494 * Counts the number of profiled function calls sitting under
495 * the given point in the call graph. Not the most efficient algo.
496 *
497 * @param $stack Array:
498 * @param $start Integer:
499 * @return Integer
500 * @private
501 */
502 function calltreeCount( $stack, $start ) {
503 $level = $stack[$start][1];
504 $count = 0;
505 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
506 $count ++;
507 }
508 return $count;
509 }
510
511 /**
512 * Log the whole profiling data into the database.
513 */
514 public function logData() {
515 global $wgProfilePerHost, $wgProfileToDatabase;
516
517 # Do not log anything if database is readonly (bug 5375)
518 if( wfReadOnly() || !$wgProfileToDatabase ) {
519 return;
520 }
521
522 $dbw = wfGetDB( DB_MASTER );
523 if( !is_object( $dbw ) ) {
524 return;
525 }
526
527 if( $wgProfilePerHost ) {
528 $pfhost = wfHostname();
529 } else {
530 $pfhost = '';
531 }
532
533 try {
534 $this->collateData();
535
536 foreach( $this->mCollated as $name => $elapsed ) {
537 $eventCount = $this->mCalls[$name];
538 $timeSum = (float) ($elapsed * 1000);
539 $memorySum = (float)$this->mMemory[$name];
540 $name = substr( $name, 0, 255 );
541
542 // Kludge
543 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
544 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
545
546 $dbw->update( 'profiling',
547 array(
548 "pf_count=pf_count+{$eventCount}",
549 "pf_time=pf_time+{$timeSum}",
550 "pf_memory=pf_memory+{$memorySum}",
551 ),
552 array(
553 'pf_name' => $name,
554 'pf_server' => $pfhost,
555 ),
556 __METHOD__ );
557
558 $rc = $dbw->affectedRows();
559 if ( $rc == 0 ) {
560 $dbw->insert( 'profiling', array ( 'pf_name' => $name, 'pf_count' => $eventCount,
561 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
562 __METHOD__, array ( 'IGNORE' ) );
563 }
564 // When we upgrade to mysql 4.1, the insert+update
565 // can be merged into just a insert with this construct added:
566 // "ON DUPLICATE KEY UPDATE ".
567 // "pf_count=pf_count + VALUES(pf_count), ".
568 // "pf_time=pf_time + VALUES(pf_time)";
569 }
570 } catch ( DBError $e ) {}
571 }
572
573 /**
574 * Get the function name of the current profiling section
575 * @return
576 */
577 function getCurrentSection() {
578 $elt = end( $this->mWorkStack );
579 return $elt[0];
580 }
581
582 /**
583 * Add an entry in the debug log file
584 *
585 * @param string $s to output
586 */
587 function debug( $s ) {
588 if( defined( 'MW_COMPILED' ) || function_exists( 'wfDebug' ) ) {
589 wfDebug( $s );
590 }
591 }
592
593 /**
594 * Get the content type sent out to the client.
595 * Used for profilers that output instead of store data.
596 * @return string
597 */
598 protected function getContentType() {
599 foreach ( headers_list() as $header ) {
600 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
601 return $m[1];
602 }
603 }
604 return null;
605 }
606 }