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
209 function getCallTree() {
210 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
214 * Recursive function the format the current profiling array into a tree
216 * @param $stack profiling array
218 function remapCallTree( $stack ) {
219 if( count( $stack ) < 2 ){
223 for( $max = count( $stack ) - 1; $max > 0; ){
224 /* Find all items under this entry */
225 $level = $stack[$max][1];
227 for( $i = $max -1; $i >= 0; $i-- ){
228 if( $stack[$i][1] > $level ){
229 $working[] = $stack[$i];
234 $working = $this->remapCallTree( array_reverse( $working ) );
236 foreach( $working as $item ){
237 array_push( $output, $item );
239 array_unshift( $output, $stack[$max] );
242 array_unshift( $outputs, $output );
245 foreach( $outputs as $output ){
246 foreach( $output as $item ){
254 * Callback to get a formatted line for the call tree
256 function getCallTreeLine( $entry ) {
257 list( $fname, $level, $start, /* $x */, $end) = $entry;
258 $delta = $end - $start;
259 $space = str_repeat(' ', $level);
260 # The ugly double sprintf is to work around a PHP bug,
261 # which has been fixed in recent releases.
262 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
266 if ( $this->mTimeMetric
=== 'user' ) {
267 return $this->getUserTime();
269 return microtime( true );
273 function getUserTime() {
275 return $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
278 private function getInitialTime() {
279 global $wgRequestTime, $wgRUstart;
281 if ( $this->mTimeMetric
=== 'user' ) {
282 if ( count( $wgRUstart ) ) {
283 return $wgRUstart['ru_utime.tv_sec'] +
$wgRUstart['ru_utime.tv_usec'] / 1e6
;
288 if ( empty( $wgRequestTime ) ) {
291 return $wgRequestTime;
296 protected function collateData() {
297 if ( $this->mCollateDone
) {
300 $this->mCollateDone
= true;
304 $this->mCollated
= array();
305 $this->mCalls
= array();
306 $this->mMemory
= array();
308 # Estimate profiling overhead
309 $profileCount = count($this->mStack
);
310 self
::calculateOverhead( $profileCount );
312 # First, subtract the overhead!
313 $overheadTotal = $overheadMemory = $overheadInternal = array();
314 foreach( $this->mStack
as $entry ){
318 $elapsed = $end - $start;
319 $memory = $entry[5] - $entry[3];
321 if( $fname == '-overhead-total' ){
322 $overheadTotal[] = $elapsed;
323 $overheadMemory[] = $memory;
325 elseif( $fname == '-overhead-internal' ){
326 $overheadInternal[] = $elapsed;
329 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
330 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
331 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
334 foreach( $this->mStack
as $index => $entry ){
338 $elapsed = $end - $start;
340 $memory = $entry[5] - $entry[3];
341 $subcalls = $this->calltreeCount( $this->mStack
, $index );
343 if( !preg_match( '/^-overhead/', $fname ) ){
344 # Adjust for profiling overhead (except special values with elapsed=0
346 $elapsed -= $overheadInternal;
347 $elapsed -= ($subcalls * $overheadTotal);
348 $memory -= ($subcalls * $overheadMemory);
352 if( !array_key_exists( $fname, $this->mCollated
) ){
353 $this->mCollated
[$fname] = 0;
354 $this->mCalls
[$fname] = 0;
355 $this->mMemory
[$fname] = 0;
356 $this->mMin
[$fname] = 1 << 24;
357 $this->mMax
[$fname] = 0;
358 $this->mOverhead
[$fname] = 0;
361 $this->mCollated
[$fname] +
= $elapsed;
362 $this->mCalls
[$fname]++
;
363 $this->mMemory
[$fname] +
= $memory;
364 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
365 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
366 $this->mOverhead
[$fname] +
= $subcalls;
369 $this->mCalls
['-overhead-total'] = $profileCount;
370 arsort( $this->mCollated
, SORT_NUMERIC
);
374 * Returns a list of profiled functions.
378 function getFunctionReport() {
379 $this->collateData();
382 $nameWidth = $width - 65;
383 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
384 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
385 $prof = "\nProfiling data\n";
386 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
388 $total = isset( $this->mCollated
['-total'] ) ?
$this->mCollated
['-total'] : 0;
390 foreach( $this->mCollated
as $fname => $elapsed ){
391 $calls = $this->mCalls
[$fname];
392 $percent = $total ?
100. * $elapsed / $total : 0;
393 $memory = $this->mMemory
[$fname];
394 $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]);
396 $prof .= "\nTotal: $total\n\n";
402 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
404 protected static function calculateOverhead( $profileCount ) {
405 wfProfileIn( '-overhead-total' );
406 for( $i = 0; $i < $profileCount; $i++
){
407 wfProfileIn( '-overhead-internal' );
408 wfProfileOut( '-overhead-internal' );
410 wfProfileOut( '-overhead-total' );
414 * Counts the number of profiled function calls sitting under
415 * the given point in the call graph. Not the most efficient algo.
417 * @param $stack Array:
418 * @param $start Integer:
422 function calltreeCount($stack, $start) {
423 $level = $stack[$start][1];
425 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
432 * Log the whole profiling data into the database.
434 public function logData(){
435 global $wgProfilePerHost, $wgProfileToDatabase;
437 # Do not log anything if database is readonly (bug 5375)
438 if( wfReadOnly() ||
!$wgProfileToDatabase ) {
442 $dbw = wfGetDB( DB_MASTER
);
443 if( !is_object( $dbw ) ) {
447 $errorState = $dbw->ignoreErrors( true );
449 if( $wgProfilePerHost ){
450 $pfhost = wfHostname();
455 $this->collateData();
457 foreach( $this->mCollated
as $name => $elapsed ){
458 $eventCount = $this->mCalls
[$name];
459 $timeSum = (float) ($elapsed * 1000);
460 $memorySum = (float)$this->mMemory
[$name];
461 $name = substr($name, 0, 255);
464 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
465 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
467 $dbw->update( 'profiling',
469 "pf_count=pf_count+{$eventCount}",
470 "pf_time=pf_time+{$timeSum}",
471 "pf_memory=pf_memory+{$memorySum}",
475 'pf_server' => $pfhost,
479 $rc = $dbw->affectedRows();
481 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
482 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
483 __METHOD__
, array ('IGNORE'));
485 // When we upgrade to mysql 4.1, the insert+update
486 // can be merged into just a insert with this construct added:
487 // "ON DUPLICATE KEY UPDATE ".
488 // "pf_count=pf_count + VALUES(pf_count), ".
489 // "pf_time=pf_time + VALUES(pf_time)";
492 $dbw->ignoreErrors( $errorState );
496 * Get the function name of the current profiling section
498 function getCurrentSection() {
499 $elt = end( $this->mWorkStack
);
504 * Add an entry in the debug log file
506 * @param $s String to output
508 function debug( $s ) {
509 if( defined( 'MW_COMPILED' ) ||
function_exists( 'wfDebug' ) ) {