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 // Push an entry for the pre-profile setup time onto the stack
52 $initial = $this->getInitialTime();
53 if ( $initial !== null ) {
54 $this->mWorkStack
[] = array( '-total', 0, $initial, 0 );
55 $this->mStack
[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
57 $this->profileIn( '-total' );
65 public static function instance() {
66 if( is_null( self
::$__instance ) ) {
68 if( is_array( $wgProfiler ) ) {
69 if( !isset( $wgProfiler['class'] ) ) {
70 wfDebug( __METHOD__
. " called without \$wgProfiler['class']"
71 . " set, falling back to ProfilerStub for safety\n" );
72 $class = 'ProfilerStub';
74 $class = $wgProfiler['class'];
76 self
::$__instance = new $class( $wgProfiler );
77 } elseif( $wgProfiler instanceof Profiler
) {
78 self
::$__instance = $wgProfiler; // back-compat
80 wfDebug( __METHOD__
. ' called with bogus $wgProfiler setting,'
81 . " falling back to ProfilerStub for safety\n" );
82 self
::$__instance = new ProfilerStub( $wgProfiler );
85 return self
::$__instance;
89 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
90 * @param $p Profiler object
92 public static function setInstance( Profiler
$p ) {
93 self
::$__instance = $p;
97 * Return whether this a stub profiler
101 public function isStub() {
105 public function setProfileID( $id ) {
106 $this->mProfileID
= $id;
109 public function getProfileID() {
110 if ( $this->mProfileID
=== false ) {
113 return $this->mProfileID
;
118 * Called by wfProfieIn()
120 * @param $functionname String
122 public function profileIn( $functionname ) {
123 global $wgDebugFunctionEntry;
124 if( $wgDebugFunctionEntry ){
125 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
128 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
132 * Called by wfProfieOut()
134 * @param $functionname String
136 public function profileOut( $functionname ) {
137 global $wgDebugFunctionEntry;
138 $memory = memory_get_usage();
139 $time = $this->getTime();
141 if( $wgDebugFunctionEntry ){
142 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
145 $bit = array_pop($this->mWorkStack
);
148 $this->debug("Profiling error, !\$bit: $functionname\n");
150 //if( $wgDebugProfiling ){
151 if( $functionname == 'close' ){
152 $message = "Profile section ended by close(): {$bit[0]}";
153 $this->debug( "$message\n" );
154 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
156 elseif( $bit[0] != $functionname ){
157 $message = "Profiling error: in({$bit[0]}), out($functionname)";
158 $this->debug( "$message\n" );
159 $this->mStack
[] = array( $message, 0, 0.0, 0, 0.0, 0 );
164 $this->mStack
[] = $bit;
169 * Close opened profiling sections
171 public function close() {
172 while( count( $this->mWorkStack
) ){
173 $this->profileOut( 'close' );
178 * Mark this call as templated or not
182 function setTemplated( $t ) {
183 $this->mTemplated
= $t;
187 * Returns a profiling output to be stored in debug file
191 public function getOutput() {
192 global $wgDebugFunctionEntry, $wgProfileCallTree;
193 $wgDebugFunctionEntry = false;
195 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
196 return "No profiling output\n";
199 if( $wgProfileCallTree ) {
200 return $this->getCallTree();
202 return $this->getFunctionReport();
207 * Returns a tree of function call instead of a list of functions
210 function getCallTree() {
211 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
215 * Recursive function the format the current profiling array into a tree
217 * @param $stack array profiling array
220 function remapCallTree( $stack ) {
221 if( count( $stack ) < 2 ){
225 for( $max = count( $stack ) - 1; $max > 0; ){
226 /* Find all items under this entry */
227 $level = $stack[$max][1];
229 for( $i = $max -1; $i >= 0; $i-- ){
230 if( $stack[$i][1] > $level ){
231 $working[] = $stack[$i];
236 $working = $this->remapCallTree( array_reverse( $working ) );
238 foreach( $working as $item ){
239 array_push( $output, $item );
241 array_unshift( $output, $stack[$max] );
244 array_unshift( $outputs, $output );
247 foreach( $outputs as $output ){
248 foreach( $output as $item ){
256 * Callback to get a formatted line for the call tree
259 function getCallTreeLine( $entry ) {
260 list( $fname, $level, $start, /* $x */, $end) = $entry;
261 $delta = $end - $start;
262 $space = str_repeat(' ', $level);
263 # The ugly double sprintf is to work around a PHP bug,
264 # which has been fixed in recent releases.
265 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
269 if ( $this->mTimeMetric
=== 'user' ) {
270 return $this->getUserTime();
272 return microtime( true );
276 function getUserTime() {
278 return $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
281 private function getInitialTime() {
282 global $wgRequestTime, $wgRUstart;
284 if ( $this->mTimeMetric
=== 'user' ) {
285 if ( count( $wgRUstart ) ) {
286 return $wgRUstart['ru_utime.tv_sec'] +
$wgRUstart['ru_utime.tv_usec'] / 1e6
;
291 if ( empty( $wgRequestTime ) ) {
294 return $wgRequestTime;
299 protected function collateData() {
300 if ( $this->mCollateDone
) {
303 $this->mCollateDone
= true;
307 $this->mCollated
= array();
308 $this->mCalls
= array();
309 $this->mMemory
= array();
311 # Estimate profiling overhead
312 $profileCount = count($this->mStack
);
313 self
::calculateOverhead( $profileCount );
315 # First, subtract the overhead!
316 $overheadTotal = $overheadMemory = $overheadInternal = array();
317 foreach( $this->mStack
as $entry ){
321 $elapsed = $end - $start;
322 $memory = $entry[5] - $entry[3];
324 if( $fname == '-overhead-total' ){
325 $overheadTotal[] = $elapsed;
326 $overheadMemory[] = $memory;
328 elseif( $fname == '-overhead-internal' ){
329 $overheadInternal[] = $elapsed;
332 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
333 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
334 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
337 foreach( $this->mStack
as $index => $entry ){
341 $elapsed = $end - $start;
343 $memory = $entry[5] - $entry[3];
344 $subcalls = $this->calltreeCount( $this->mStack
, $index );
346 if( !preg_match( '/^-overhead/', $fname ) ){
347 # Adjust for profiling overhead (except special values with elapsed=0
349 $elapsed -= $overheadInternal;
350 $elapsed -= ($subcalls * $overheadTotal);
351 $memory -= ($subcalls * $overheadMemory);
355 if( !array_key_exists( $fname, $this->mCollated
) ){
356 $this->mCollated
[$fname] = 0;
357 $this->mCalls
[$fname] = 0;
358 $this->mMemory
[$fname] = 0;
359 $this->mMin
[$fname] = 1 << 24;
360 $this->mMax
[$fname] = 0;
361 $this->mOverhead
[$fname] = 0;
364 $this->mCollated
[$fname] +
= $elapsed;
365 $this->mCalls
[$fname]++
;
366 $this->mMemory
[$fname] +
= $memory;
367 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
368 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
369 $this->mOverhead
[$fname] +
= $subcalls;
372 $this->mCalls
['-overhead-total'] = $profileCount;
373 arsort( $this->mCollated
, SORT_NUMERIC
);
377 * Returns a list of profiled functions.
381 function getFunctionReport() {
382 $this->collateData();
385 $nameWidth = $width - 65;
386 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
387 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
388 $prof = "\nProfiling data\n";
389 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
391 $total = isset( $this->mCollated
['-total'] ) ?
$this->mCollated
['-total'] : 0;
393 foreach( $this->mCollated
as $fname => $elapsed ){
394 $calls = $this->mCalls
[$fname];
395 $percent = $total ?
100. * $elapsed / $total : 0;
396 $memory = $this->mMemory
[$fname];
397 $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]);
399 $prof .= "\nTotal: $total\n\n";
405 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
407 protected static function calculateOverhead( $profileCount ) {
408 wfProfileIn( '-overhead-total' );
409 for( $i = 0; $i < $profileCount; $i++
){
410 wfProfileIn( '-overhead-internal' );
411 wfProfileOut( '-overhead-internal' );
413 wfProfileOut( '-overhead-total' );
417 * Counts the number of profiled function calls sitting under
418 * the given point in the call graph. Not the most efficient algo.
420 * @param $stack Array:
421 * @param $start Integer:
425 function calltreeCount($stack, $start) {
426 $level = $stack[$start][1];
428 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
435 * Log the whole profiling data into the database.
437 public function logData(){
438 global $wgProfilePerHost, $wgProfileToDatabase;
440 # Do not log anything if database is readonly (bug 5375)
441 if( wfReadOnly() ||
!$wgProfileToDatabase ) {
445 $dbw = wfGetDB( DB_MASTER
);
446 if( !is_object( $dbw ) ) {
450 $errorState = $dbw->ignoreErrors( true );
452 if( $wgProfilePerHost ){
453 $pfhost = wfHostname();
458 $this->collateData();
460 foreach( $this->mCollated
as $name => $elapsed ){
461 $eventCount = $this->mCalls
[$name];
462 $timeSum = (float) ($elapsed * 1000);
463 $memorySum = (float)$this->mMemory
[$name];
464 $name = substr($name, 0, 255);
467 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
468 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
470 $dbw->update( 'profiling',
472 "pf_count=pf_count+{$eventCount}",
473 "pf_time=pf_time+{$timeSum}",
474 "pf_memory=pf_memory+{$memorySum}",
478 'pf_server' => $pfhost,
482 $rc = $dbw->affectedRows();
484 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
485 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
486 __METHOD__
, array ('IGNORE'));
488 // When we upgrade to mysql 4.1, the insert+update
489 // can be merged into just a insert with this construct added:
490 // "ON DUPLICATE KEY UPDATE ".
491 // "pf_count=pf_count + VALUES(pf_count), ".
492 // "pf_time=pf_time + VALUES(pf_time)";
495 $dbw->ignoreErrors( $errorState );
499 * Get the function name of the current profiling section
502 function getCurrentSection() {
503 $elt = end( $this->mWorkStack
);
508 * Add an entry in the debug log file
510 * @param $s String to output
512 function debug( $s ) {
513 if( defined( 'MW_COMPILED' ) ||
function_exists( 'wfDebug' ) ) {