3 * @defgroup Profiler Profiler
7 * This file is only included if profiling is enabled
11 * Begin profiling of a function
12 * @param $functionname String: name of the function we will profile
14 function wfProfileIn( $functionname ) {
16 if ( $wgProfiler instanceof Profiler ||
isset( $wgProfiler['class'] ) ) {
17 Profiler
::instance()->profileIn( $functionname );
22 * Stop profiling of a function
23 * @param $functionname String: name of the function we have profiled
25 function wfProfileOut( $functionname = 'missing' ) {
27 if ( $wgProfiler instanceof Profiler ||
isset( $wgProfiler['class'] ) ) {
28 Profiler
::instance()->profileOut( $functionname );
37 protected $mStack = array(), $mWorkStack = array (), $mCollated = array (),
38 $mCalls = array (), $mTotals = array ();
39 protected $mTimeMetric = 'wall';
40 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
41 private static $__instance = null;
43 function __construct( $params ) {
44 if ( isset( $params['timeMetric'] ) ) {
45 $this->mTimeMetric
= $params['timeMetric'];
47 if ( isset( $params['profileID'] ) ) {
48 $this->mProfileID
= $params['profileID'];
51 $this->addInitialStack();
58 public static function instance() {
59 if( is_null( self
::$__instance ) ) {
61 if( is_array( $wgProfiler ) ) {
62 if( !isset( $wgProfiler['class'] ) ) {
63 wfDebug( __METHOD__
. " called without \$wgProfiler['class']"
64 . " set, falling back to ProfilerStub for safety\n" );
65 $class = 'ProfilerStub';
67 $class = $wgProfiler['class'];
69 self
::$__instance = new $class( $wgProfiler );
70 } elseif( $wgProfiler instanceof Profiler
) {
71 self
::$__instance = $wgProfiler; // back-compat
73 wfDebug( __METHOD__
. ' called with bogus $wgProfiler setting,'
74 . " falling back to ProfilerStub for safety\n" );
75 self
::$__instance = new ProfilerStub( $wgProfiler );
78 return self
::$__instance;
82 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
83 * @param $p Profiler object
85 public static function setInstance( Profiler
$p ) {
86 self
::$__instance = $p;
90 * Return whether this a stub profiler
94 public function isStub() {
98 public function setProfileID( $id ) {
99 $this->mProfileID
= $id;
102 public function getProfileID() {
103 if ( $this->mProfileID
=== false ) {
106 return $this->mProfileID
;
111 * Add the inital item in the stack.
113 protected function addInitialStack() {
114 // Push an entry for the pre-profile setup time onto the stack
115 $initial = $this->getInitialTime();
116 if ( $initial !== null ) {
117 $this->mWorkStack
[] = array( '-total', 0, $initial, 0 );
118 $this->mStack
[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
120 $this->profileIn( '-total' );
125 * Called by wfProfieIn()
127 * @param $functionname String
129 public function profileIn( $functionname ) {
130 global $wgDebugFunctionEntry;
131 if( $wgDebugFunctionEntry ){
132 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
135 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
139 * Called by wfProfieOut()
141 * @param $functionname String
143 public function profileOut( $functionname ) {
144 global $wgDebugFunctionEntry;
145 $memory = memory_get_usage();
146 $time = $this->getTime();
148 if( $wgDebugFunctionEntry ){
149 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
152 $bit = array_pop($this->mWorkStack
);
155 $this->debug("Profiling error, !\$bit: $functionname\n");
157 //if( $wgDebugProfiling ){
158 if( $functionname == 'close' ){
159 $message = "Profile section ended by close(): {$bit[0]}";
160 $this->debug( "$message\n" );
161 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
163 elseif( $bit[0] != $functionname ){
164 $message = "Profiling error: in({$bit[0]}), out($functionname)";
165 $this->debug( "$message\n" );
166 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
171 $this->mStack
[] = $bit;
176 * Close opened profiling sections
178 public function close() {
179 while( count( $this->mWorkStack
) ){
180 $this->profileOut( 'close' );
185 * Mark this call as templated or not
189 function setTemplated( $t ) {
190 $this->mTemplated
= $t;
194 * Returns a profiling output to be stored in debug file
198 public function getOutput() {
199 global $wgDebugFunctionEntry, $wgProfileCallTree;
200 $wgDebugFunctionEntry = false;
202 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
203 return "No profiling output\n";
206 if( $wgProfileCallTree ) {
207 return $this->getCallTree();
209 return $this->getFunctionReport();
214 * Returns a tree of function call instead of a list of functions
217 function getCallTree() {
218 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
222 * Recursive function the format the current profiling array into a tree
224 * @param $stack array profiling array
227 function remapCallTree( $stack ) {
228 if( count( $stack ) < 2 ){
232 for( $max = count( $stack ) - 1; $max > 0; ){
233 /* Find all items under this entry */
234 $level = $stack[$max][1];
236 for( $i = $max -1; $i >= 0; $i-- ){
237 if( $stack[$i][1] > $level ){
238 $working[] = $stack[$i];
243 $working = $this->remapCallTree( array_reverse( $working ) );
245 foreach( $working as $item ){
246 array_push( $output, $item );
248 array_unshift( $output, $stack[$max] );
251 array_unshift( $outputs, $output );
254 foreach( $outputs as $output ){
255 foreach( $output as $item ){
263 * Callback to get a formatted line for the call tree
266 function getCallTreeLine( $entry ) {
267 list( $fname, $level, $start, /* $x */, $end) = $entry;
268 $delta = $end - $start;
269 $space = str_repeat(' ', $level);
270 # The ugly double sprintf is to work around a PHP bug,
271 # which has been fixed in recent releases.
272 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
276 if ( $this->mTimeMetric
=== 'user' ) {
277 return $this->getUserTime();
279 return microtime( true );
283 function getUserTime() {
285 return $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
288 private function getInitialTime() {
289 global $wgRequestTime, $wgRUstart;
291 if ( $this->mTimeMetric
=== 'user' ) {
292 if ( count( $wgRUstart ) ) {
293 return $wgRUstart['ru_utime.tv_sec'] +
$wgRUstart['ru_utime.tv_usec'] / 1e6
;
298 if ( empty( $wgRequestTime ) ) {
301 return $wgRequestTime;
306 protected function collateData() {
307 if ( $this->mCollateDone
) {
310 $this->mCollateDone
= true;
314 $this->mCollated
= array();
315 $this->mCalls
= array();
316 $this->mMemory
= array();
318 # Estimate profiling overhead
319 $profileCount = count($this->mStack
);
320 self
::calculateOverhead( $profileCount );
322 # First, subtract the overhead!
323 $overheadTotal = $overheadMemory = $overheadInternal = array();
324 foreach( $this->mStack
as $entry ){
328 $elapsed = $end - $start;
329 $memory = $entry[5] - $entry[3];
331 if( $fname == '-overhead-total' ){
332 $overheadTotal[] = $elapsed;
333 $overheadMemory[] = $memory;
335 elseif( $fname == '-overhead-internal' ){
336 $overheadInternal[] = $elapsed;
339 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
340 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
341 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
344 foreach( $this->mStack
as $index => $entry ){
348 $elapsed = $end - $start;
350 $memory = $entry[5] - $entry[3];
351 $subcalls = $this->calltreeCount( $this->mStack
, $index );
353 if( !preg_match( '/^-overhead/', $fname ) ){
354 # Adjust for profiling overhead (except special values with elapsed=0
356 $elapsed -= $overheadInternal;
357 $elapsed -= ($subcalls * $overheadTotal);
358 $memory -= ($subcalls * $overheadMemory);
362 if( !array_key_exists( $fname, $this->mCollated
) ){
363 $this->mCollated
[$fname] = 0;
364 $this->mCalls
[$fname] = 0;
365 $this->mMemory
[$fname] = 0;
366 $this->mMin
[$fname] = 1 << 24;
367 $this->mMax
[$fname] = 0;
368 $this->mOverhead
[$fname] = 0;
371 $this->mCollated
[$fname] +
= $elapsed;
372 $this->mCalls
[$fname]++
;
373 $this->mMemory
[$fname] +
= $memory;
374 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
375 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
376 $this->mOverhead
[$fname] +
= $subcalls;
379 $this->mCalls
['-overhead-total'] = $profileCount;
380 arsort( $this->mCollated
, SORT_NUMERIC
);
384 * Returns a list of profiled functions.
388 function getFunctionReport() {
389 $this->collateData();
392 $nameWidth = $width - 65;
393 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
394 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
395 $prof = "\nProfiling data\n";
396 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
398 $total = isset( $this->mCollated
['-total'] ) ?
$this->mCollated
['-total'] : 0;
400 foreach( $this->mCollated
as $fname => $elapsed ){
401 $calls = $this->mCalls
[$fname];
402 $percent = $total ?
100. * $elapsed / $total : 0;
403 $memory = $this->mMemory
[$fname];
404 $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]);
406 $prof .= "\nTotal: $total\n\n";
412 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
414 protected static function calculateOverhead( $profileCount ) {
415 wfProfileIn( '-overhead-total' );
416 for( $i = 0; $i < $profileCount; $i++
){
417 wfProfileIn( '-overhead-internal' );
418 wfProfileOut( '-overhead-internal' );
420 wfProfileOut( '-overhead-total' );
424 * Counts the number of profiled function calls sitting under
425 * the given point in the call graph. Not the most efficient algo.
427 * @param $stack Array:
428 * @param $start Integer:
432 function calltreeCount($stack, $start) {
433 $level = $stack[$start][1];
435 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
442 * Log the whole profiling data into the database.
444 public function logData(){
445 global $wgProfilePerHost, $wgProfileToDatabase;
447 # Do not log anything if database is readonly (bug 5375)
448 if( wfReadOnly() ||
!$wgProfileToDatabase ) {
452 $dbw = wfGetDB( DB_MASTER
);
453 if( !is_object( $dbw ) ) {
457 $errorState = $dbw->ignoreErrors( true );
459 if( $wgProfilePerHost ){
460 $pfhost = wfHostname();
465 $this->collateData();
467 foreach( $this->mCollated
as $name => $elapsed ){
468 $eventCount = $this->mCalls
[$name];
469 $timeSum = (float) ($elapsed * 1000);
470 $memorySum = (float)$this->mMemory
[$name];
471 $name = substr($name, 0, 255);
474 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
475 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
477 $dbw->update( 'profiling',
479 "pf_count=pf_count+{$eventCount}",
480 "pf_time=pf_time+{$timeSum}",
481 "pf_memory=pf_memory+{$memorySum}",
485 'pf_server' => $pfhost,
489 $rc = $dbw->affectedRows();
491 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
492 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
493 __METHOD__
, array ('IGNORE'));
495 // When we upgrade to mysql 4.1, the insert+update
496 // can be merged into just a insert with this construct added:
497 // "ON DUPLICATE KEY UPDATE ".
498 // "pf_count=pf_count + VALUES(pf_count), ".
499 // "pf_time=pf_time + VALUES(pf_time)";
502 $dbw->ignoreErrors( $errorState );
506 * Get the function name of the current profiling section
509 function getCurrentSection() {
510 $elt = end( $this->mWorkStack
);
515 * Add an entry in the debug log file
517 * @param $s String to output
519 function debug( $s ) {
520 if( defined( 'MW_COMPILED' ) ||
function_exists( 'wfDebug' ) ) {