Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / profiler / Profiler.php
blob194bafed2b69fda7c04a1a47a61f239e1d7fe7ce
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 global $wgProfiler;
35 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
36 Profiler::instance()->profileIn( $functionname );
40 /**
41 * Stop profiling of a function
42 * @param string $functionname name of the function we have profiled
44 function wfProfileOut( $functionname = 'missing' ) {
45 global $wgProfiler;
46 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
47 Profiler::instance()->profileOut( $functionname );
51 /**
52 * Class for handling function-scope profiling
54 * @since 1.22
56 class ProfileSection {
57 protected $name; // string; method name
58 protected $enabled = false; // boolean; whether profiling is enabled
60 /**
61 * Begin profiling of a function and return an object that ends profiling of
62 * the function when that object leaves scope. As long as the object is not
63 * specifically linked to other objects, it will fall out of scope at the same
64 * moment that the function to be profiled terminates.
66 * This is typically called like:
67 * <code>$section = new ProfileSection( __METHOD__ );</code>
69 * @param string $name Name of the function to profile
71 public function __construct( $name ) {
72 $this->name = $name;
73 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
74 Profiler::instance();
76 if ( Profiler::$__instance && !( Profiler::$__instance instanceof ProfilerStub ) ) {
77 $this->enabled = true;
78 Profiler::$__instance->profileIn( $this->name );
82 function __destruct() {
83 if ( $this->enabled ) {
84 Profiler::$__instance->profileOut( $this->name );
89 /**
90 * @ingroup Profiler
91 * @todo document
93 class Profiler {
94 protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
95 $mCalls = array(), $mTotals = array();
96 protected $mTimeMetric = 'wall';
97 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
99 /** @var Profiler */
100 public static $__instance = null; // do not call this outside Profiler and ProfileSection
102 function __construct( $params ) {
103 if ( isset( $params['timeMetric'] ) ) {
104 $this->mTimeMetric = $params['timeMetric'];
106 if ( isset( $params['profileID'] ) ) {
107 $this->mProfileID = $params['profileID'];
110 $this->addInitialStack();
114 * Singleton
115 * @return Profiler
117 public static function instance() {
118 if ( is_null( self::$__instance ) ) {
119 global $wgProfiler;
120 if ( is_array( $wgProfiler ) ) {
121 if ( !isset( $wgProfiler['class'] ) ) {
122 wfDebug( __METHOD__ . " called without \$wgProfiler['class']"
123 . " set, falling back to ProfilerStub for safety\n" );
124 $class = 'ProfilerStub';
125 } else {
126 $class = $wgProfiler['class'];
128 self::$__instance = new $class( $wgProfiler );
129 } elseif ( $wgProfiler instanceof Profiler ) {
130 self::$__instance = $wgProfiler; // back-compat
131 } else {
132 wfDebug( __METHOD__ . ' called with bogus $wgProfiler setting,'
133 . " falling back to ProfilerStub for safety\n" );
134 self::$__instance = new ProfilerStub( $wgProfiler );
137 return self::$__instance;
141 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
142 * @param $p Profiler object
144 public static function setInstance( Profiler $p ) {
145 self::$__instance = $p;
149 * Return whether this a stub profiler
151 * @return Boolean
153 public function isStub() {
154 return false;
158 * Return whether this profiler stores data
160 * @see Profiler::logData()
161 * @return Boolean
163 public function isPersistent() {
164 return true;
167 public function setProfileID( $id ) {
168 $this->mProfileID = $id;
171 public function getProfileID() {
172 if ( $this->mProfileID === false ) {
173 return wfWikiID();
174 } else {
175 return $this->mProfileID;
180 * Add the inital item in the stack.
182 protected function addInitialStack() {
183 // Push an entry for the pre-profile setup time onto the stack
184 $initial = $this->getInitialTime();
185 if ( $initial !== null ) {
186 $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
187 $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
188 } else {
189 $this->profileIn( '-total' );
194 * Called by wfProfieIn()
196 * @param $functionname String
198 public function profileIn( $functionname ) {
199 global $wgDebugFunctionEntry;
200 if ( $wgDebugFunctionEntry ) {
201 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
204 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
208 * Called by wfProfieOut()
210 * @param $functionname String
212 public function profileOut( $functionname ) {
213 global $wgDebugFunctionEntry;
214 $memory = memory_get_usage();
215 $time = $this->getTime();
217 if ( $wgDebugFunctionEntry ) {
218 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
221 $bit = array_pop( $this->mWorkStack );
223 if ( !$bit ) {
224 $this->debug( "Profiling error, !\$bit: $functionname\n" );
225 } else {
226 //if( $wgDebugProfiling ) {
227 if ( $functionname == 'close' ) {
228 $message = "Profile section ended by close(): {$bit[0]}";
229 $this->debug( "$message\n" );
230 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
231 } elseif ( $bit[0] != $functionname ) {
232 $message = "Profiling error: in({$bit[0]}), out($functionname)";
233 $this->debug( "$message\n" );
234 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
237 $bit[] = $time;
238 $bit[] = $memory;
239 $this->mStack[] = $bit;
244 * Close opened profiling sections
246 public function close() {
247 while ( count( $this->mWorkStack ) ) {
248 $this->profileOut( 'close' );
253 * Mark this call as templated or not
255 * @param $t Boolean
257 function setTemplated( $t ) {
258 $this->mTemplated = $t;
262 * Returns a profiling output to be stored in debug file
264 * @return String
266 public function getOutput() {
267 global $wgDebugFunctionEntry, $wgProfileCallTree;
268 $wgDebugFunctionEntry = false;
270 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
271 return "No profiling output\n";
274 if ( $wgProfileCallTree ) {
275 return $this->getCallTree();
276 } else {
277 return $this->getFunctionReport();
282 * Returns a tree of function call instead of a list of functions
283 * @return string
285 function getCallTree() {
286 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
290 * Recursive function the format the current profiling array into a tree
292 * @param array $stack profiling array
293 * @return array
295 function remapCallTree( $stack ) {
296 if ( count( $stack ) < 2 ) {
297 return $stack;
299 $outputs = array();
300 for ( $max = count( $stack ) - 1; $max > 0; ) {
301 /* Find all items under this entry */
302 $level = $stack[$max][1];
303 $working = array();
304 for ( $i = $max -1; $i >= 0; $i-- ) {
305 if ( $stack[$i][1] > $level ) {
306 $working[] = $stack[$i];
307 } else {
308 break;
311 $working = $this->remapCallTree( array_reverse( $working ) );
312 $output = array();
313 foreach ( $working as $item ) {
314 array_push( $output, $item );
316 array_unshift( $output, $stack[$max] );
317 $max = $i;
319 array_unshift( $outputs, $output );
321 $final = array();
322 foreach ( $outputs as $output ) {
323 foreach ( $output as $item ) {
324 $final[] = $item;
327 return $final;
331 * Callback to get a formatted line for the call tree
332 * @return string
334 function getCallTreeLine( $entry ) {
335 list( $fname, $level, $start, /* $x */, $end ) = $entry;
336 $delta = $end - $start;
337 $space = str_repeat( ' ', $level );
338 # The ugly double sprintf is to work around a PHP bug,
339 # which has been fixed in recent releases.
340 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
344 * Get the initial time of the request, based either on $wgRequestTime or
345 * $wgRUstart. Will return null if not able to find data.
347 * @param string|false $metric metric to use, with the following possibilities:
348 * - user: User CPU time (without system calls)
349 * - cpu: Total CPU time (user and system calls)
350 * - wall (or any other string): elapsed time
351 * - false (default): will fall back to default metric
352 * @return float|null
354 function getTime( $metric = false ) {
355 if ( $metric === false ) {
356 $metric = $this->mTimeMetric;
359 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
360 if ( !function_exists( 'getrusage' ) ) {
361 return 0;
363 $ru = getrusage();
364 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
365 if ( $metric === 'cpu' ) {
366 # This is the time of system calls, added to the user time
367 # it gives the total CPU time
368 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
370 return $time;
371 } else {
372 return microtime( true );
377 * Get the initial time of the request, based either on $wgRequestTime or
378 * $wgRUstart. Will return null if not able to find data.
380 * @param string|false $metric metric to use, with the following possibilities:
381 * - user: User CPU time (without system calls)
382 * - cpu: Total CPU time (user and system calls)
383 * - wall (or any other string): elapsed time
384 * - false (default): will fall back to default metric
385 * @return float|null
387 protected function getInitialTime( $metric = false ) {
388 global $wgRequestTime, $wgRUstart;
390 if ( $metric === false ) {
391 $metric = $this->mTimeMetric;
394 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
395 if ( !count( $wgRUstart ) ) {
396 return null;
399 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
400 if ( $metric === 'cpu' ) {
401 # This is the time of system calls, added to the user time
402 # it gives the total CPU time
403 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
405 return $time;
406 } else {
407 if ( empty( $wgRequestTime ) ) {
408 return null;
409 } else {
410 return $wgRequestTime;
415 protected function collateData() {
416 if ( $this->mCollateDone ) {
417 return;
419 $this->mCollateDone = true;
421 $this->close();
423 $this->mCollated = array();
424 $this->mCalls = array();
425 $this->mMemory = array();
427 # Estimate profiling overhead
428 $profileCount = count( $this->mStack );
429 self::calculateOverhead( $profileCount );
431 # First, subtract the overhead!
432 $overheadTotal = $overheadMemory = $overheadInternal = array();
433 foreach ( $this->mStack as $entry ) {
434 $fname = $entry[0];
435 $start = $entry[2];
436 $end = $entry[4];
437 $elapsed = $end - $start;
438 $memory = $entry[5] - $entry[3];
440 if ( $fname == '-overhead-total' ) {
441 $overheadTotal[] = $elapsed;
442 $overheadMemory[] = $memory;
443 } elseif ( $fname == '-overhead-internal' ) {
444 $overheadInternal[] = $elapsed;
447 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
448 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
449 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
451 # Collate
452 foreach ( $this->mStack as $index => $entry ) {
453 $fname = $entry[0];
454 $start = $entry[2];
455 $end = $entry[4];
456 $elapsed = $end - $start;
458 $memory = $entry[5] - $entry[3];
459 $subcalls = $this->calltreeCount( $this->mStack, $index );
461 if ( !preg_match( '/^-overhead/', $fname ) ) {
462 # Adjust for profiling overhead (except special values with elapsed=0
463 if ( $elapsed ) {
464 $elapsed -= $overheadInternal;
465 $elapsed -= ( $subcalls * $overheadTotal );
466 $memory -= ( $subcalls * $overheadMemory );
470 if ( !array_key_exists( $fname, $this->mCollated ) ) {
471 $this->mCollated[$fname] = 0;
472 $this->mCalls[$fname] = 0;
473 $this->mMemory[$fname] = 0;
474 $this->mMin[$fname] = 1 << 24;
475 $this->mMax[$fname] = 0;
476 $this->mOverhead[$fname] = 0;
479 $this->mCollated[$fname] += $elapsed;
480 $this->mCalls[$fname]++;
481 $this->mMemory[$fname] += $memory;
482 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
483 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
484 $this->mOverhead[$fname] += $subcalls;
487 $this->mCalls['-overhead-total'] = $profileCount;
488 arsort( $this->mCollated, SORT_NUMERIC );
492 * Returns a list of profiled functions.
494 * @return string
496 function getFunctionReport() {
497 $this->collateData();
499 $width = 140;
500 $nameWidth = $width - 65;
501 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
502 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
503 $prof = "\nProfiling data\n";
504 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
506 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
508 foreach ( $this->mCollated as $fname => $elapsed ) {
509 $calls = $this->mCalls[$fname];
510 $percent = $total ? 100. * $elapsed / $total : 0;
511 $memory = $this->mMemory[$fname];
512 $prof .= sprintf( $format,
513 substr( $fname, 0, $nameWidth ),
514 $calls,
515 (float) ( $elapsed * 1000 ),
516 (float) ( $elapsed * 1000 ) / $calls,
517 $percent,
518 $memory,
519 ( $this->mMin[$fname] * 1000.0 ),
520 ( $this->mMax[$fname] * 1000.0 ),
521 $this->mOverhead[$fname]
524 $prof .= "\nTotal: $total\n\n";
526 return $prof;
530 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
532 protected static function calculateOverhead( $profileCount ) {
533 wfProfileIn( '-overhead-total' );
534 for ( $i = 0; $i < $profileCount; $i++ ) {
535 wfProfileIn( '-overhead-internal' );
536 wfProfileOut( '-overhead-internal' );
538 wfProfileOut( '-overhead-total' );
542 * Counts the number of profiled function calls sitting under
543 * the given point in the call graph. Not the most efficient algo.
545 * @param $stack Array:
546 * @param $start Integer:
547 * @return Integer
548 * @private
550 function calltreeCount( $stack, $start ) {
551 $level = $stack[$start][1];
552 $count = 0;
553 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
554 $count ++;
556 return $count;
560 * Log the whole profiling data into the database.
562 public function logData() {
563 global $wgProfilePerHost, $wgProfileToDatabase;
565 # Do not log anything if database is readonly (bug 5375)
566 if ( wfReadOnly() || !$wgProfileToDatabase ) {
567 return;
570 $dbw = wfGetDB( DB_MASTER );
571 if ( !is_object( $dbw ) ) {
572 return;
575 if ( $wgProfilePerHost ) {
576 $pfhost = wfHostname();
577 } else {
578 $pfhost = '';
581 try {
582 $this->collateData();
584 foreach ( $this->mCollated as $name => $elapsed ) {
585 $eventCount = $this->mCalls[$name];
586 $timeSum = (float) ( $elapsed * 1000 );
587 $memorySum = (float)$this->mMemory[$name];
588 $name = substr( $name, 0, 255 );
590 // Kludge
591 $timeSum = $timeSum >= 0 ? $timeSum : 0;
592 $memorySum = $memorySum >= 0 ? $memorySum : 0;
594 $dbw->update( 'profiling',
595 array(
596 "pf_count=pf_count+{$eventCount}",
597 "pf_time=pf_time+{$timeSum}",
598 "pf_memory=pf_memory+{$memorySum}",
600 array(
601 'pf_name' => $name,
602 'pf_server' => $pfhost,
604 __METHOD__ );
606 $rc = $dbw->affectedRows();
607 if ( $rc == 0 ) {
608 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
609 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
610 __METHOD__, array( 'IGNORE' ) );
612 // When we upgrade to mysql 4.1, the insert+update
613 // can be merged into just a insert with this construct added:
614 // "ON DUPLICATE KEY UPDATE ".
615 // "pf_count=pf_count + VALUES(pf_count), ".
616 // "pf_time=pf_time + VALUES(pf_time)";
618 } catch ( DBError $e ) {}
622 * Get the function name of the current profiling section
623 * @return
625 function getCurrentSection() {
626 $elt = end( $this->mWorkStack );
627 return $elt[0];
631 * Add an entry in the debug log file
633 * @param string $s to output
635 function debug( $s ) {
636 if ( function_exists( 'wfDebug' ) ) {
637 wfDebug( $s );
642 * Get the content type sent out to the client.
643 * Used for profilers that output instead of store data.
644 * @return string
646 protected function getContentType() {
647 foreach ( headers_list() as $header ) {
648 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
649 return $m[1];
652 return null;