Fix TOC display for printing
[mediawiki.git] / includes / profiler / Profiler.php
blob2282a3af401b4e82fc753e39d47f4e8dba7e7360
1 <?php
2 /**
3 * Base class and functions for profiling.
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.
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.
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
20 * @file
21 * @ingroup Profiler
22 * This file is only included if profiling is enabled
25 /**
26 * @defgroup Profiler Profiler
29 /**
30 * Begin profiling of a function
31 * @param string $functionname name of the function we will profile
33 function wfProfileIn( $functionname ) {
34 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
35 Profiler::instance();
37 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
38 Profiler::$__instance->profileIn( $functionname );
42 /**
43 * Stop profiling of a function
44 * @param string $functionname name of the function we have profiled
46 function wfProfileOut( $functionname = 'missing' ) {
47 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
48 Profiler::instance();
50 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
51 Profiler::$__instance->profileOut( $functionname );
55 /**
56 * Class for handling function-scope profiling
58 * @since 1.22
60 class ProfileSection {
61 protected $name; // string; method name
62 protected $enabled = false; // boolean; whether profiling is enabled
64 /**
65 * Begin profiling of a function and return an object that ends profiling of
66 * the function when that object leaves scope. As long as the object is not
67 * specifically linked to other objects, it will fall out of scope at the same
68 * moment that the function to be profiled terminates.
70 * This is typically called like:
71 * <code>$section = new ProfileSection( __METHOD__ );</code>
73 * @param string $name Name of the function to profile
75 public function __construct( $name ) {
76 $this->name = $name;
77 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
78 Profiler::instance();
80 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
81 $this->enabled = true;
82 Profiler::$__instance->profileIn( $this->name );
86 function __destruct() {
87 if ( $this->enabled ) {
88 Profiler::$__instance->profileOut( $this->name );
93 /**
94 * @ingroup Profiler
95 * @todo document
97 class Profiler {
98 protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
99 $mCalls = array(), $mTotals = array();
100 protected $mTimeMetric = 'wall';
101 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
103 protected $mDBLockThreshold = 5.0; // float; seconds
104 /** @var Array DB/server name => (active trx count,timestamp) */
105 protected $mDBTrxHoldingLocks = array();
106 /** @var Array DB/server name => list of (method, elapsed time) */
107 protected $mDBTrxMethodTimes = array();
109 /** @var Profiler */
110 public static $__instance = null; // do not call this outside Profiler and ProfileSection
112 function __construct( $params ) {
113 if ( isset( $params['timeMetric'] ) ) {
114 $this->mTimeMetric = $params['timeMetric'];
116 if ( isset( $params['profileID'] ) ) {
117 $this->mProfileID = $params['profileID'];
120 $this->addInitialStack();
124 * Singleton
125 * @return Profiler
127 public static function instance() {
128 if ( self::$__instance === null ) {
129 global $wgProfiler;
130 if ( is_array( $wgProfiler ) ) {
131 if ( !isset( $wgProfiler['class'] ) ) {
132 $class = 'ProfilerStub';
133 } else {
134 $class = $wgProfiler['class'];
136 self::$__instance = new $class( $wgProfiler );
137 } elseif ( $wgProfiler instanceof Profiler ) {
138 self::$__instance = $wgProfiler; // back-compat
139 } else {
140 self::$__instance = new ProfilerStub( $wgProfiler );
143 return self::$__instance;
147 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
148 * @param $p Profiler object
150 public static function setInstance( Profiler $p ) {
151 self::$__instance = $p;
155 * Return whether this a stub profiler
157 * @return Boolean
159 public function isStub() {
160 return false;
164 * Return whether this profiler stores data
166 * @see Profiler::logData()
167 * @return Boolean
169 public function isPersistent() {
170 return true;
173 public function setProfileID( $id ) {
174 $this->mProfileID = $id;
177 public function getProfileID() {
178 if ( $this->mProfileID === false ) {
179 return wfWikiID();
180 } else {
181 return $this->mProfileID;
186 * Add the inital item in the stack.
188 protected function addInitialStack() {
189 // Push an entry for the pre-profile setup time onto the stack
190 $initial = $this->getInitialTime();
191 if ( $initial !== null ) {
192 $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
193 $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
194 } else {
195 $this->profileIn( '-total' );
200 * Called by wfProfieIn()
202 * @param $functionname String
204 public function profileIn( $functionname ) {
205 global $wgDebugFunctionEntry;
206 if ( $wgDebugFunctionEntry ) {
207 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
210 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
214 * Called by wfProfieOut()
216 * @param $functionname String
218 public function profileOut( $functionname ) {
219 global $wgDebugFunctionEntry;
220 $memory = memory_get_usage();
221 $time = $this->getTime();
223 if ( $wgDebugFunctionEntry ) {
224 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
227 $bit = array_pop( $this->mWorkStack );
229 if ( !$bit ) {
230 $this->debug( "Profiling error, !\$bit: $functionname\n" );
231 } else {
232 if ( $functionname == 'close' ) {
233 $message = "Profile section ended by close(): {$bit[0]}";
234 $this->debug( "$message\n" );
235 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
236 } elseif ( $bit[0] != $functionname ) {
237 $message = "Profiling error: in({$bit[0]}), out($functionname)";
238 $this->debug( "$message\n" );
239 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
241 $bit[] = $time;
242 $bit[] = $memory;
243 $this->mStack[] = $bit;
244 $this->updateTrxProfiling( $functionname, $time );
249 * Close opened profiling sections
251 public function close() {
252 while ( count( $this->mWorkStack ) ) {
253 $this->profileOut( 'close' );
258 * Mark a DB as in a transaction with one or more writes pending
260 * Note that there can be multiple connections to a single DB.
262 * @param string $server DB server
263 * @param string $db DB name
265 public function transactionWritingIn( $server, $db ) {
266 $name = "{$server} ({$db})";
267 if ( isset( $this->mDBTrxHoldingLocks[$name] ) ) {
268 ++$this->mDBTrxHoldingLocks[$name]['refs'];
269 } else {
270 $this->mDBTrxHoldingLocks[$name] = array( 'refs' => 1, 'start' => microtime( true ) );
271 $this->mDBTrxMethodTimes[$name] = array();
276 * Register the name and time of a method for slow DB trx detection
278 * @param string $method Function name
279 * @param float $realtime Wal time ellapsed
281 protected function updateTrxProfiling( $method, $realtime ) {
282 if ( !$this->mDBTrxHoldingLocks ) {
283 return; // short-circuit
284 // @TODO: hardcoded check is a tad janky (what about FOR UPDATE?)
285 } elseif ( !preg_match( '/^query-m: (?!SELECT)/', $method )
286 && $realtime < $this->mDBLockThreshold )
288 return; // not a DB master query nor slow enough
290 $now = microtime( true );
291 foreach ( $this->mDBTrxHoldingLocks as $name => $info ) {
292 // Hacky check to exclude entries from before the first TRX write
293 if ( ( $now - $realtime ) >= $info['start'] ) {
294 $this->mDBTrxMethodTimes[$name][] = array( $method, $realtime );
300 * Mark a DB as no longer in a transaction
302 * This will check if locks are possibly held for longer than
303 * needed and log any affected transactions to a special DB log.
304 * Note that there can be multiple connections to a single DB.
306 * @param string $server DB server
307 * @param string $db DB name
309 public function transactionWritingOut( $server, $db ) {
310 $name = "{$server} ({$db})";
311 if ( --$this->mDBTrxHoldingLocks[$name]['refs'] <= 0 ) {
312 $slow = false;
313 foreach ( $this->mDBTrxMethodTimes[$name] as $info ) {
314 list( $method, $realtime ) = $info;
315 if ( $realtime >= $this->mDBLockThreshold ) {
316 $slow = true;
317 break;
320 if ( $slow ) {
321 $dbs = implode( ', ', array_keys( $this->mDBTrxHoldingLocks ) );
322 $msg = "Sub-optimal transaction on DB(s) {$dbs}:\n";
323 foreach ( $this->mDBTrxMethodTimes[$name] as $i => $info ) {
324 list( $method, $realtime ) = $info;
325 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, $realtime, $method );
327 wfDebugLog( 'DBPerformance', $msg );
329 unset( $this->mDBTrxHoldingLocks[$name] );
330 unset( $this->mDBTrxMethodTimes[$name] );
335 * Mark this call as templated or not
337 * @param $t Boolean
339 function setTemplated( $t ) {
340 $this->mTemplated = $t;
344 * Returns a profiling output to be stored in debug file
346 * @return String
348 public function getOutput() {
349 global $wgDebugFunctionEntry, $wgProfileCallTree;
350 $wgDebugFunctionEntry = false;
352 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
353 return "No profiling output\n";
356 if ( $wgProfileCallTree ) {
357 return $this->getCallTree();
358 } else {
359 return $this->getFunctionReport();
364 * Returns a tree of function call instead of a list of functions
365 * @return string
367 function getCallTree() {
368 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
372 * Recursive function the format the current profiling array into a tree
374 * @param array $stack profiling array
375 * @return array
377 function remapCallTree( $stack ) {
378 if ( count( $stack ) < 2 ) {
379 return $stack;
381 $outputs = array();
382 for ( $max = count( $stack ) - 1; $max > 0; ) {
383 /* Find all items under this entry */
384 $level = $stack[$max][1];
385 $working = array();
386 for ( $i = $max -1; $i >= 0; $i-- ) {
387 if ( $stack[$i][1] > $level ) {
388 $working[] = $stack[$i];
389 } else {
390 break;
393 $working = $this->remapCallTree( array_reverse( $working ) );
394 $output = array();
395 foreach ( $working as $item ) {
396 array_push( $output, $item );
398 array_unshift( $output, $stack[$max] );
399 $max = $i;
401 array_unshift( $outputs, $output );
403 $final = array();
404 foreach ( $outputs as $output ) {
405 foreach ( $output as $item ) {
406 $final[] = $item;
409 return $final;
413 * Callback to get a formatted line for the call tree
414 * @return string
416 function getCallTreeLine( $entry ) {
417 list( $fname, $level, $start, /* $x */, $end ) = $entry;
418 $delta = $end - $start;
419 $space = str_repeat( ' ', $level );
420 # The ugly double sprintf is to work around a PHP bug,
421 # which has been fixed in recent releases.
422 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
426 * Get the initial time of the request, based either on $wgRequestTime or
427 * $wgRUstart. Will return null if not able to find data.
429 * @param string|false $metric metric to use, with the following possibilities:
430 * - user: User CPU time (without system calls)
431 * - cpu: Total CPU time (user and system calls)
432 * - wall (or any other string): elapsed time
433 * - false (default): will fall back to default metric
434 * @return float|null
436 function getTime( $metric = false ) {
437 if ( $metric === false ) {
438 $metric = $this->mTimeMetric;
441 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
442 if ( !function_exists( 'getrusage' ) ) {
443 return 0;
445 $ru = getrusage();
446 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
447 if ( $metric === 'cpu' ) {
448 # This is the time of system calls, added to the user time
449 # it gives the total CPU time
450 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
452 return $time;
453 } else {
454 return microtime( true );
459 * Get the initial time of the request, based either on $wgRequestTime or
460 * $wgRUstart. Will return null if not able to find data.
462 * @param string|false $metric metric to use, with the following possibilities:
463 * - user: User CPU time (without system calls)
464 * - cpu: Total CPU time (user and system calls)
465 * - wall (or any other string): elapsed time
466 * - false (default): will fall back to default metric
467 * @return float|null
469 protected function getInitialTime( $metric = false ) {
470 global $wgRequestTime, $wgRUstart;
472 if ( $metric === false ) {
473 $metric = $this->mTimeMetric;
476 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
477 if ( !count( $wgRUstart ) ) {
478 return null;
481 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
482 if ( $metric === 'cpu' ) {
483 # This is the time of system calls, added to the user time
484 # it gives the total CPU time
485 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
487 return $time;
488 } else {
489 if ( empty( $wgRequestTime ) ) {
490 return null;
491 } else {
492 return $wgRequestTime;
497 protected function collateData() {
498 if ( $this->mCollateDone ) {
499 return;
501 $this->mCollateDone = true;
503 $this->close();
505 $this->mCollated = array();
506 $this->mCalls = array();
507 $this->mMemory = array();
509 # Estimate profiling overhead
510 $profileCount = count( $this->mStack );
511 self::calculateOverhead( $profileCount );
513 # First, subtract the overhead!
514 $overheadTotal = $overheadMemory = $overheadInternal = array();
515 foreach ( $this->mStack as $entry ) {
516 $fname = $entry[0];
517 $start = $entry[2];
518 $end = $entry[4];
519 $elapsed = $end - $start;
520 $memory = $entry[5] - $entry[3];
522 if ( $fname == '-overhead-total' ) {
523 $overheadTotal[] = $elapsed;
524 $overheadMemory[] = $memory;
525 } elseif ( $fname == '-overhead-internal' ) {
526 $overheadInternal[] = $elapsed;
529 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
530 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
531 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
533 # Collate
534 foreach ( $this->mStack as $index => $entry ) {
535 $fname = $entry[0];
536 $start = $entry[2];
537 $end = $entry[4];
538 $elapsed = $end - $start;
540 $memory = $entry[5] - $entry[3];
541 $subcalls = $this->calltreeCount( $this->mStack, $index );
543 if ( !preg_match( '/^-overhead/', $fname ) ) {
544 # Adjust for profiling overhead (except special values with elapsed=0
545 if ( $elapsed ) {
546 $elapsed -= $overheadInternal;
547 $elapsed -= ( $subcalls * $overheadTotal );
548 $memory -= ( $subcalls * $overheadMemory );
552 if ( !array_key_exists( $fname, $this->mCollated ) ) {
553 $this->mCollated[$fname] = 0;
554 $this->mCalls[$fname] = 0;
555 $this->mMemory[$fname] = 0;
556 $this->mMin[$fname] = 1 << 24;
557 $this->mMax[$fname] = 0;
558 $this->mOverhead[$fname] = 0;
561 $this->mCollated[$fname] += $elapsed;
562 $this->mCalls[$fname]++;
563 $this->mMemory[$fname] += $memory;
564 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
565 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
566 $this->mOverhead[$fname] += $subcalls;
569 $this->mCalls['-overhead-total'] = $profileCount;
570 arsort( $this->mCollated, SORT_NUMERIC );
574 * Returns a list of profiled functions.
576 * @return string
578 function getFunctionReport() {
579 $this->collateData();
581 $width = 140;
582 $nameWidth = $width - 65;
583 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
584 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
585 $prof = "\nProfiling data\n";
586 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
588 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
590 foreach ( $this->mCollated as $fname => $elapsed ) {
591 $calls = $this->mCalls[$fname];
592 $percent = $total ? 100. * $elapsed / $total : 0;
593 $memory = $this->mMemory[$fname];
594 $prof .= sprintf( $format,
595 substr( $fname, 0, $nameWidth ),
596 $calls,
597 (float)( $elapsed * 1000 ),
598 (float)( $elapsed * 1000 ) / $calls,
599 $percent,
600 $memory,
601 ( $this->mMin[$fname] * 1000.0 ),
602 ( $this->mMax[$fname] * 1000.0 ),
603 $this->mOverhead[$fname]
606 $prof .= "\nTotal: $total\n\n";
608 return $prof;
612 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
614 protected static function calculateOverhead( $profileCount ) {
615 wfProfileIn( '-overhead-total' );
616 for ( $i = 0; $i < $profileCount; $i++ ) {
617 wfProfileIn( '-overhead-internal' );
618 wfProfileOut( '-overhead-internal' );
620 wfProfileOut( '-overhead-total' );
624 * Counts the number of profiled function calls sitting under
625 * the given point in the call graph. Not the most efficient algo.
627 * @param $stack Array:
628 * @param $start Integer:
629 * @return Integer
630 * @private
632 function calltreeCount( $stack, $start ) {
633 $level = $stack[$start][1];
634 $count = 0;
635 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
636 $count ++;
638 return $count;
642 * Log the whole profiling data into the database.
644 public function logData() {
645 global $wgProfilePerHost, $wgProfileToDatabase;
647 # Do not log anything if database is readonly (bug 5375)
648 if ( wfReadOnly() || !$wgProfileToDatabase ) {
649 return;
652 $dbw = wfGetDB( DB_MASTER );
653 if ( !is_object( $dbw ) ) {
654 return;
657 if ( $wgProfilePerHost ) {
658 $pfhost = wfHostname();
659 } else {
660 $pfhost = '';
663 try {
664 $this->collateData();
666 foreach ( $this->mCollated as $name => $elapsed ) {
667 $eventCount = $this->mCalls[$name];
668 $timeSum = (float)( $elapsed * 1000 );
669 $memorySum = (float)$this->mMemory[$name];
670 $name = substr( $name, 0, 255 );
672 // Kludge
673 $timeSum = $timeSum >= 0 ? $timeSum : 0;
674 $memorySum = $memorySum >= 0 ? $memorySum : 0;
676 $dbw->update( 'profiling',
677 array(
678 "pf_count=pf_count+{$eventCount}",
679 "pf_time=pf_time+{$timeSum}",
680 "pf_memory=pf_memory+{$memorySum}",
682 array(
683 'pf_name' => $name,
684 'pf_server' => $pfhost,
686 __METHOD__ );
688 $rc = $dbw->affectedRows();
689 if ( $rc == 0 ) {
690 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
691 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
692 __METHOD__, array( 'IGNORE' ) );
694 // When we upgrade to mysql 4.1, the insert+update
695 // can be merged into just a insert with this construct added:
696 // "ON DUPLICATE KEY UPDATE ".
697 // "pf_count=pf_count + VALUES(pf_count), ".
698 // "pf_time=pf_time + VALUES(pf_time)";
700 } catch ( DBError $e ) {}
704 * Get the function name of the current profiling section
705 * @return
707 function getCurrentSection() {
708 $elt = end( $this->mWorkStack );
709 return $elt[0];
713 * Add an entry in the debug log file
715 * @param string $s to output
717 function debug( $s ) {
718 if ( function_exists( 'wfDebug' ) ) {
719 wfDebug( $s );
724 * Get the content type sent out to the client.
725 * Used for profilers that output instead of store data.
726 * @return string
728 protected function getContentType() {
729 foreach ( headers_list() as $header ) {
730 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
731 return $m[1];
734 return null;