Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / profiler / Profiler.php
blob49d961ef166528fb47ff629e1115f2237171f13b
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 * @ingroup Profiler
53 * @todo document
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;
62 function __construct( $params ) {
63 if ( isset( $params['timeMetric'] ) ) {
64 $this->mTimeMetric = $params['timeMetric'];
66 if ( isset( $params['profileID'] ) ) {
67 $this->mProfileID = $params['profileID'];
70 $this->addInitialStack();
73 /**
74 * Singleton
75 * @return Profiler
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'];
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 );
97 return self::$__instance;
101 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
102 * @param $p Profiler object
104 public static function setInstance( Profiler $p ) {
105 self::$__instance = $p;
109 * Return whether this a stub profiler
111 * @return Boolean
113 public function isStub() {
114 return false;
118 * Return whether this profiler stores data
120 * @see Profiler::logData()
121 * @return Boolean
123 public function isPersistent() {
124 return true;
127 public function setProfileID( $id ) {
128 $this->mProfileID = $id;
131 public function getProfileID() {
132 if ( $this->mProfileID === false ) {
133 return wfWikiID();
134 } else {
135 return $this->mProfileID;
140 * Add the inital item in the stack.
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' );
154 * Called by wfProfieIn()
156 * @param $functionname String
158 public function profileIn( $functionname ) {
159 global $wgDebugFunctionEntry;
160 if ( $wgDebugFunctionEntry ) {
161 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
164 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
168 * Called by wfProfieOut()
170 * @param $functionname String
172 public function profileOut( $functionname ) {
173 global $wgDebugFunctionEntry;
174 $memory = memory_get_usage();
175 $time = $this->getTime();
177 if ( $wgDebugFunctionEntry ) {
178 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
181 $bit = array_pop( $this->mWorkStack );
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 } elseif ( $bit[0] != $functionname ) {
192 $message = "Profiling error: in({$bit[0]}), out($functionname)";
193 $this->debug( "$message\n" );
194 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
197 $bit[] = $time;
198 $bit[] = $memory;
199 $this->mStack[] = $bit;
204 * Close opened profiling sections
206 public function close() {
207 while ( count( $this->mWorkStack ) ) {
208 $this->profileOut( 'close' );
213 * Mark this call as templated or not
215 * @param $t Boolean
217 function setTemplated( $t ) {
218 $this->mTemplated = $t;
222 * Returns a profiling output to be stored in debug file
224 * @return String
226 public function getOutput() {
227 global $wgDebugFunctionEntry, $wgProfileCallTree;
228 $wgDebugFunctionEntry = false;
230 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
231 return "No profiling output\n";
234 if ( $wgProfileCallTree ) {
235 return $this->getCallTree();
236 } else {
237 return $this->getFunctionReport();
242 * Returns a tree of function call instead of a list of functions
243 * @return string
245 function getCallTree() {
246 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
250 * Recursive function the format the current profiling array into a tree
252 * @param array $stack profiling array
253 * @return array
255 function remapCallTree( $stack ) {
256 if ( count( $stack ) < 2 ) {
257 return $stack;
259 $outputs = array();
260 for ( $max = count( $stack ) - 1; $max > 0; ) {
261 /* Find all items under this entry */
262 $level = $stack[$max][1];
263 $working = array();
264 for ( $i = $max -1; $i >= 0; $i-- ) {
265 if ( $stack[$i][1] > $level ) {
266 $working[] = $stack[$i];
267 } else {
268 break;
271 $working = $this->remapCallTree( array_reverse( $working ) );
272 $output = array();
273 foreach ( $working as $item ) {
274 array_push( $output, $item );
276 array_unshift( $output, $stack[$max] );
277 $max = $i;
279 array_unshift( $outputs, $output );
281 $final = array();
282 foreach ( $outputs as $output ) {
283 foreach ( $output as $item ) {
284 $final[] = $item;
287 return $final;
291 * Callback to get a formatted line for the call tree
292 * @return string
294 function getCallTreeLine( $entry ) {
295 list( $fname, $level, $start, /* $x */, $end ) = $entry;
296 $delta = $end - $start;
297 $space = str_repeat( ' ', $level );
298 # The ugly double sprintf is to work around a PHP bug,
299 # which has been fixed in recent releases.
300 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
304 * Get the initial time of the request, based either on $wgRequestTime or
305 * $wgRUstart. Will return null if not able to find data.
307 * @param string|false $metric metric to use, with the following possibilities:
308 * - user: User CPU time (without system calls)
309 * - cpu: Total CPU time (user and system calls)
310 * - wall (or any other string): elapsed time
311 * - false (default): will fall back to default metric
312 * @return float|null
314 function getTime( $metric = false ) {
315 if ( $metric === false ) {
316 $metric = $this->mTimeMetric;
319 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
320 if ( !function_exists( 'getrusage' ) ) {
321 return 0;
323 $ru = getrusage();
324 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
325 if ( $metric === 'cpu' ) {
326 # This is the time of system calls, added to the user time
327 # it gives the total CPU time
328 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
330 return $time;
331 } else {
332 return microtime( true );
337 * Get the initial time of the request, based either on $wgRequestTime or
338 * $wgRUstart. Will return null if not able to find data.
340 * @param string|false $metric metric to use, with the following possibilities:
341 * - user: User CPU time (without system calls)
342 * - cpu: Total CPU time (user and system calls)
343 * - wall (or any other string): elapsed time
344 * - false (default): will fall back to default metric
345 * @return float|null
347 protected function getInitialTime( $metric = false ) {
348 global $wgRequestTime, $wgRUstart;
350 if ( $metric === false ) {
351 $metric = $this->mTimeMetric;
354 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
355 if ( !count( $wgRUstart ) ) {
356 return null;
359 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
360 if ( $metric === 'cpu' ) {
361 # This is the time of system calls, added to the user time
362 # it gives the total CPU time
363 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
365 return $time;
366 } else {
367 if ( empty( $wgRequestTime ) ) {
368 return null;
369 } else {
370 return $wgRequestTime;
375 protected function collateData() {
376 if ( $this->mCollateDone ) {
377 return;
379 $this->mCollateDone = true;
381 $this->close();
383 $this->mCollated = array();
384 $this->mCalls = array();
385 $this->mMemory = array();
387 # Estimate profiling overhead
388 $profileCount = count( $this->mStack );
389 self::calculateOverhead( $profileCount );
391 # First, subtract the overhead!
392 $overheadTotal = $overheadMemory = $overheadInternal = array();
393 foreach ( $this->mStack as $entry ) {
394 $fname = $entry[0];
395 $start = $entry[2];
396 $end = $entry[4];
397 $elapsed = $end - $start;
398 $memory = $entry[5] - $entry[3];
400 if ( $fname == '-overhead-total' ) {
401 $overheadTotal[] = $elapsed;
402 $overheadMemory[] = $memory;
403 } elseif ( $fname == '-overhead-internal' ) {
404 $overheadInternal[] = $elapsed;
407 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
408 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
409 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
411 # Collate
412 foreach ( $this->mStack as $index => $entry ) {
413 $fname = $entry[0];
414 $start = $entry[2];
415 $end = $entry[4];
416 $elapsed = $end - $start;
418 $memory = $entry[5] - $entry[3];
419 $subcalls = $this->calltreeCount( $this->mStack, $index );
421 if ( !preg_match( '/^-overhead/', $fname ) ) {
422 # Adjust for profiling overhead (except special values with elapsed=0
423 if ( $elapsed ) {
424 $elapsed -= $overheadInternal;
425 $elapsed -= ($subcalls * $overheadTotal);
426 $memory -= ($subcalls * $overheadMemory);
430 if ( !array_key_exists( $fname, $this->mCollated ) ) {
431 $this->mCollated[$fname] = 0;
432 $this->mCalls[$fname] = 0;
433 $this->mMemory[$fname] = 0;
434 $this->mMin[$fname] = 1 << 24;
435 $this->mMax[$fname] = 0;
436 $this->mOverhead[$fname] = 0;
439 $this->mCollated[$fname] += $elapsed;
440 $this->mCalls[$fname]++;
441 $this->mMemory[$fname] += $memory;
442 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
443 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
444 $this->mOverhead[$fname] += $subcalls;
447 $this->mCalls['-overhead-total'] = $profileCount;
448 arsort( $this->mCollated, SORT_NUMERIC );
452 * Returns a list of profiled functions.
454 * @return string
456 function getFunctionReport() {
457 $this->collateData();
459 $width = 140;
460 $nameWidth = $width - 65;
461 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
462 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
463 $prof = "\nProfiling data\n";
464 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
466 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
468 foreach ( $this->mCollated as $fname => $elapsed ) {
469 $calls = $this->mCalls[$fname];
470 $percent = $total ? 100. * $elapsed / $total : 0;
471 $memory = $this->mMemory[$fname];
472 $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] );
474 $prof .= "\nTotal: $total\n\n";
476 return $prof;
480 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
482 protected static function calculateOverhead( $profileCount ) {
483 wfProfileIn( '-overhead-total' );
484 for ( $i = 0; $i < $profileCount; $i++ ) {
485 wfProfileIn( '-overhead-internal' );
486 wfProfileOut( '-overhead-internal' );
488 wfProfileOut( '-overhead-total' );
492 * Counts the number of profiled function calls sitting under
493 * the given point in the call graph. Not the most efficient algo.
495 * @param $stack Array:
496 * @param $start Integer:
497 * @return Integer
498 * @private
500 function calltreeCount( $stack, $start ) {
501 $level = $stack[$start][1];
502 $count = 0;
503 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
504 $count ++;
506 return $count;
510 * Log the whole profiling data into the database.
512 public function logData() {
513 global $wgProfilePerHost, $wgProfileToDatabase;
515 # Do not log anything if database is readonly (bug 5375)
516 if ( wfReadOnly() || !$wgProfileToDatabase ) {
517 return;
520 $dbw = wfGetDB( DB_MASTER );
521 if ( !is_object( $dbw ) ) {
522 return;
525 if ( $wgProfilePerHost ) {
526 $pfhost = wfHostname();
527 } else {
528 $pfhost = '';
531 try {
532 $this->collateData();
534 foreach ( $this->mCollated as $name => $elapsed ) {
535 $eventCount = $this->mCalls[$name];
536 $timeSum = (float) ($elapsed * 1000);
537 $memorySum = (float)$this->mMemory[$name];
538 $name = substr( $name, 0, 255 );
540 // Kludge
541 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
542 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
544 $dbw->update( 'profiling',
545 array(
546 "pf_count=pf_count+{$eventCount}",
547 "pf_time=pf_time+{$timeSum}",
548 "pf_memory=pf_memory+{$memorySum}",
550 array(
551 'pf_name' => $name,
552 'pf_server' => $pfhost,
554 __METHOD__ );
556 $rc = $dbw->affectedRows();
557 if ( $rc == 0 ) {
558 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
559 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
560 __METHOD__, array( 'IGNORE' ) );
562 // When we upgrade to mysql 4.1, the insert+update
563 // can be merged into just a insert with this construct added:
564 // "ON DUPLICATE KEY UPDATE ".
565 // "pf_count=pf_count + VALUES(pf_count), ".
566 // "pf_time=pf_time + VALUES(pf_time)";
568 } catch ( DBError $e ) {}
572 * Get the function name of the current profiling section
573 * @return
575 function getCurrentSection() {
576 $elt = end( $this->mWorkStack );
577 return $elt[0];
581 * Add an entry in the debug log file
583 * @param string $s to output
585 function debug( $s ) {
586 if ( defined( 'MW_COMPILED' ) || function_exists( 'wfDebug' ) ) {
587 wfDebug( $s );
592 * Get the content type sent out to the client.
593 * Used for profilers that output instead of store data.
594 * @return string
596 protected function getContentType() {
597 foreach ( headers_list() as $header ) {
598 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
599 return $m[1];
602 return null;