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 ( 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 ( isset( $wgProfiler['class'] ) ) {
28 Profiler
::instance()->profileOut( $functionname );
37 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
38 var $mCalls = array (), $mTotals = array ();
39 var $mTemplated = false;
40 var $mTimeMetric = 'wall';
41 private $mCollateDone = false;
42 protected $mProfileID = false;
43 private static $__instance = null;
45 function __construct( $params ) {
46 // Push an entry for the pre-profile setup time onto the stack
47 global $wgRequestTime;
48 if ( !empty( $wgRequestTime ) ) {
49 $this->mWorkStack
[] = array( '-total', 0, $wgRequestTime, 0 );
50 $this->mStack
[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
52 $this->profileIn( '-total' );
54 if ( isset( $params['timeMetric'] ) ) {
55 $this->mTimeMetric
= $params['timeMetric'];
63 public static function instance() {
64 if( is_null( self
::$__instance ) ) {
66 if( is_array( $wgProfiler ) ) {
67 $class = isset( $wgProfiler['class'] ) ?
$wgProfiler['class'] : 'ProfilerStub';
68 self
::$__instance = new $class( $wgProfiler );
69 } elseif( $wgProfiler instanceof Profiler
) {
70 self
::$__instance = $wgProfiler; // back-compat
72 self
::$__instance = new ProfilerStub( $wgProfiler );
75 return self
::$__instance;
79 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
80 * @param $p Profiler object
82 public static function setInstance( Profiler
$p ) {
83 self
::$__instance = $p;
87 * Return whether this a stub profiler
91 public function isStub() {
95 public function setProfileID( $id ) {
96 $this->mProfileID
= $id;
99 public function getProfileID() {
100 if ( $this->mProfileID
=== false ) {
103 return $this->mProfileID
;
108 * Called by wfProfieIn()
110 * @param $functionname String
112 public function profileIn( $functionname ) {
113 global $wgDebugFunctionEntry;
114 if( $wgDebugFunctionEntry ){
115 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
118 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
122 * Called by wfProfieOut()
124 * @param $functionname String
126 public function profileOut( $functionname ) {
127 global $wgDebugFunctionEntry;
128 $memory = memory_get_usage();
129 $time = $this->getTime();
131 if( $wgDebugFunctionEntry ){
132 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
135 $bit = array_pop($this->mWorkStack
);
138 $this->debug("Profiling error, !\$bit: $functionname\n");
140 //if( $wgDebugProfiling ){
141 if( $functionname == 'close' ){
142 $message = "Profile section ended by close(): {$bit[0]}";
143 $this->debug( "$message\n" );
144 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
146 elseif( $bit[0] != $functionname ){
147 $message = "Profiling error: in({$bit[0]}), out($functionname)";
148 $this->debug( "$message\n" );
149 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
154 $this->mStack
[] = $bit;
159 * Close opened profiling sections
161 public function close() {
162 while( count( $this->mWorkStack
) ){
163 $this->profileOut( 'close' );
168 * Mark this call as templated or not
172 function setTemplated( $t ) {
173 $this->mTemplated
= $t;
177 * Returns a profiling output to be stored in debug file
181 public function getOutput() {
182 global $wgDebugFunctionEntry, $wgProfileCallTree;
183 $wgDebugFunctionEntry = false;
185 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
186 return "No profiling output\n";
189 if( $wgProfileCallTree ) {
190 return $this->getCallTree();
192 return $this->getFunctionReport();
197 * Returns a tree of function call instead of a list of functions
199 function getCallTree() {
200 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
204 * Recursive function the format the current profiling array into a tree
206 * @param $stack profiling array
208 function remapCallTree( $stack ) {
209 if( count( $stack ) < 2 ){
213 for( $max = count( $stack ) - 1; $max > 0; ){
214 /* Find all items under this entry */
215 $level = $stack[$max][1];
217 for( $i = $max -1; $i >= 0; $i-- ){
218 if( $stack[$i][1] > $level ){
219 $working[] = $stack[$i];
224 $working = $this->remapCallTree( array_reverse( $working ) );
226 foreach( $working as $item ){
227 array_push( $output, $item );
229 array_unshift( $output, $stack[$max] );
232 array_unshift( $outputs, $output );
235 foreach( $outputs as $output ){
236 foreach( $output as $item ){
244 * Callback to get a formatted line for the call tree
246 function getCallTreeLine( $entry ) {
247 list( $fname, $level, $start, /* $x */, $end) = $entry;
248 $delta = $end - $start;
249 $space = str_repeat(' ', $level);
250 # The ugly double sprintf is to work around a PHP bug,
251 # which has been fixed in recent releases.
252 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
256 if ( $this->mTimeMetric
=== 'user' ) {
257 return $this->getUserTime();
259 return microtime(true);
263 function getUserTime() {
265 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6
;
268 protected function collateData() {
269 if ( $this->mCollateDone
) {
272 $this->mCollateDone
= true;
276 $this->mCollated
= array();
277 $this->mCalls
= array();
278 $this->mMemory
= array();
280 # Estimate profiling overhead
281 $profileCount = count($this->mStack
);
282 self
::calculateOverhead( $profileCount );
284 # First, subtract the overhead!
285 $overheadTotal = $overheadMemory = $overheadInternal = array();
286 foreach( $this->mStack
as $entry ){
290 $elapsed = $end - $start;
291 $memory = $entry[5] - $entry[3];
293 if( $fname == '-overhead-total' ){
294 $overheadTotal[] = $elapsed;
295 $overheadMemory[] = $memory;
297 elseif( $fname == '-overhead-internal' ){
298 $overheadInternal[] = $elapsed;
301 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
302 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
303 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
306 foreach( $this->mStack
as $index => $entry ){
310 $elapsed = $end - $start;
312 $memory = $entry[5] - $entry[3];
313 $subcalls = $this->calltreeCount( $this->mStack
, $index );
315 if( !preg_match( '/^-overhead/', $fname ) ){
316 # Adjust for profiling overhead (except special values with elapsed=0
318 $elapsed -= $overheadInternal;
319 $elapsed -= ($subcalls * $overheadTotal);
320 $memory -= ($subcalls * $overheadMemory);
324 if( !array_key_exists( $fname, $this->mCollated
) ){
325 $this->mCollated
[$fname] = 0;
326 $this->mCalls
[$fname] = 0;
327 $this->mMemory
[$fname] = 0;
328 $this->mMin
[$fname] = 1 << 24;
329 $this->mMax
[$fname] = 0;
330 $this->mOverhead
[$fname] = 0;
333 $this->mCollated
[$fname] +
= $elapsed;
334 $this->mCalls
[$fname]++
;
335 $this->mMemory
[$fname] +
= $memory;
336 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
337 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
338 $this->mOverhead
[$fname] +
= $subcalls;
341 $this->mCalls
['-overhead-total'] = $profileCount;
342 arsort( $this->mCollated
, SORT_NUMERIC
);
346 * Returns a list of profiled functions.
347 * Also log it into the database if $wgProfileToDatabase is set to true.
349 function getFunctionReport() {
350 $this->collateData();
353 $nameWidth = $width - 65;
354 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
355 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
356 $prof = "\nProfiling data\n";
357 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
359 $total = isset( $this->mCollated
['-total'] ) ?
$this->mCollated
['-total'] : 0;
361 foreach( $this->mCollated
as $fname => $elapsed ){
362 $calls = $this->mCalls
[$fname];
363 $percent = $total ?
100. * $elapsed / $total : 0;
364 $memory = $this->mMemory
[$fname];
365 $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]);
367 $prof .= "\nTotal: $total\n\n";
373 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
375 protected static function calculateOverhead( $profileCount ) {
376 wfProfileIn( '-overhead-total' );
377 for( $i = 0; $i < $profileCount; $i++
){
378 wfProfileIn( '-overhead-internal' );
379 wfProfileOut( '-overhead-internal' );
381 wfProfileOut( '-overhead-total' );
385 * Counts the number of profiled function calls sitting under
386 * the given point in the call graph. Not the most efficient algo.
388 * @param $stack Array:
389 * @param $start Integer:
393 function calltreeCount($stack, $start) {
394 $level = $stack[$start][1];
396 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
403 * Log the whole profiling data into the database.
405 public function logData(){
406 global $wgProfilePerHost, $wgProfileToDatabase;
408 # Do not log anything if database is readonly (bug 5375)
409 if( wfReadOnly() ||
!$wgProfileToDatabase ) {
413 $dbw = wfGetDB( DB_MASTER
);
414 if( !is_object( $dbw ) ) {
418 $errorState = $dbw->ignoreErrors( true );
420 if( $wgProfilePerHost ){
421 $pfhost = wfHostname();
426 $this->collateData();
428 foreach( $this->mCollated
as $name => $elapsed ){
429 $eventCount = $this->mCalls
[$name];
430 $timeSum = (float) ($elapsed * 1000);
431 $memorySum = (float)$this->mMemory
[$name];
432 $name = substr($name, 0, 255);
435 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
436 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
438 $dbw->update( 'profiling',
440 "pf_count=pf_count+{$eventCount}",
441 "pf_time=pf_time+{$timeSum}",
442 "pf_memory=pf_memory+{$memorySum}",
446 'pf_server' => $pfhost,
450 $rc = $dbw->affectedRows();
452 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
453 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
454 __METHOD__
, array ('IGNORE'));
456 // When we upgrade to mysql 4.1, the insert+update
457 // can be merged into just a insert with this construct added:
458 // "ON DUPLICATE KEY UPDATE ".
459 // "pf_count=pf_count + VALUES(pf_count), ".
460 // "pf_time=pf_time + VALUES(pf_time)";
463 $dbw->ignoreErrors( $errorState );
467 * Get the function name of the current profiling section
469 function getCurrentSection() {
470 $elt = end( $this->mWorkStack
);
475 * Add an entry in the debug log file
477 * @param $s String to output
479 function debug( $s ) {
480 if( defined( 'MW_COMPILED' ) ||
function_exists( 'wfDebug' ) ) {