3 * @defgroup Profiler Profiler
7 * This file is only included if profiling is enabled
11 * Default profiling configuration. Permitted keys are:
12 * class : Name of Profiler or subclass to use for profiling
13 * visible : Whether to output the profile info [ProfilerSimpleText only]
16 'class' => 'ProfilerStub',
20 * Begin profiling of a function
21 * @param $functionname String: name of the function we will profile
23 function wfProfileIn( $functionname ) {
24 Profiler
::instance()->profileIn( $functionname );
28 * Stop profiling of a function
29 * @param $functionname String: name of the function we have profiled
31 function wfProfileOut( $functionname = 'missing' ) {
32 Profiler
::instance()->profileOut( $functionname );
36 * Returns a profiling output to be stored in debug file
38 function wfGetProfilingOutput() {
39 Profiler
::instance()->getOutput();
43 * Close opened profiling sections
45 function wfProfileClose() {
46 Profiler
::instance()->close();
49 if (!function_exists('memory_get_usage')) {
50 # Old PHP or --enable-memory-limit not compiled in
51 function memory_get_usage() {
61 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
62 var $mCalls = array (), $mTotals = array ();
63 var $mTemplated = false;
64 private static $__instance = null;
66 function __construct() {
67 // Push an entry for the pre-profile setup time onto the stack
68 global $wgRequestTime;
69 if ( !empty( $wgRequestTime ) ) {
70 $this->mWorkStack
[] = array( '-total', 0, $wgRequestTime, 0 );
71 $this->mStack
[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
73 $this->profileIn( '-total' );
81 public static function instance() {
82 if( is_null( self
::$__instance ) ) {
84 if( is_array( $wgProfiler ) ) {
85 $class = $wgProfiler['class'];
86 self
::$__instance = new $class( $wgProfiler );
87 } elseif( $wgProfiler instanceof Profiler
) {
88 self
::$__instance = $wgProfiler; // back-compat
90 throw new MWException( '$wgProfiler set to bogus value' );
94 return self
::$__instance;
98 * Called by wfProfieIn()
100 * @param $functionname String
102 public function profileIn( $functionname ) {
103 global $wgDebugFunctionEntry;
104 if( $wgDebugFunctionEntry ){
105 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
108 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
112 * Called by wfProfieOut()
114 * @param $functionname String
116 public function profileOut($functionname) {
117 global $wgDebugFunctionEntry;
118 $memory = memory_get_usage();
119 $time = $this->getTime();
121 if( $wgDebugFunctionEntry ){
122 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
125 $bit = array_pop($this->mWorkStack
);
128 $this->debug("Profiling error, !\$bit: $functionname\n");
130 //if( $wgDebugProfiling ){
131 if( $functionname == 'close' ){
132 $message = "Profile section ended by close(): {$bit[0]}";
133 $this->debug( "$message\n" );
134 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
136 elseif( $bit[0] != $functionname ){
137 $message = "Profiling error: in({$bit[0]}), out($functionname)";
138 $this->debug( "$message\n" );
139 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
144 $this->mStack
[] = $bit;
149 * called by wfProfileClose()
151 public function close() {
152 while( count( $this->mWorkStack
) ){
153 $this->profileOut( 'close' );
158 * Mark this call as templated or not
162 function setTemplated( $t ) {
163 $this->mTemplated
= $t;
167 * Called by wfGetProfilingOutput()
169 public function getOutput() {
170 global $wgDebugFunctionEntry, $wgProfileCallTree;
171 $wgDebugFunctionEntry = false;
173 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
174 return "No profiling output\n";
178 if( $wgProfileCallTree ) {
179 global $wgProfileToDatabase;
180 # XXX: We must call $this->getFunctionReport() to log to the DB
181 if( $wgProfileToDatabase ) {
182 $this->getFunctionReport();
184 return $this->getCallTree();
186 return $this->getFunctionReport();
191 * Returns a tree of function call instead of a list of functions
193 function getCallTree() {
194 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
198 * Recursive function the format the current profiling array into a tree
200 * @param $stack profiling array
202 function remapCallTree( $stack ) {
203 if( count( $stack ) < 2 ){
207 for( $max = count( $stack ) - 1; $max > 0; ){
208 /* Find all items under this entry */
209 $level = $stack[$max][1];
211 for( $i = $max -1; $i >= 0; $i-- ){
212 if( $stack[$i][1] > $level ){
213 $working[] = $stack[$i];
218 $working = $this->remapCallTree( array_reverse( $working ) );
220 foreach( $working as $item ){
221 array_push( $output, $item );
223 array_unshift( $output, $stack[$max] );
226 array_unshift( $outputs, $output );
229 foreach( $outputs as $output ){
230 foreach( $output as $item ){
238 * Callback to get a formatted line for the call tree
240 function getCallTreeLine( $entry ) {
241 list( $fname, $level, $start, /* $x */, $end) = $entry;
242 $delta = $end - $start;
243 $space = str_repeat(' ', $level);
244 # The ugly double sprintf is to work around a PHP bug,
245 # which has been fixed in recent releases.
246 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
250 return microtime(true);
251 #return $this->getUserTime();
254 function getUserTime() {
256 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6
;
260 * Returns a list of profiled functions.
261 * Also log it into the database if $wgProfileToDatabase is set to true.
263 function getFunctionReport() {
264 global $wgProfileToDatabase;
267 $nameWidth = $width - 65;
268 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
269 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
270 $prof = "\nProfiling data\n";
271 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
272 $this->mCollated
= array ();
273 $this->mCalls
= array ();
274 $this->mMemory
= array ();
276 # Estimate profiling overhead
277 $profileCount = count($this->mStack
);
278 self
::calculateOverhead( $profileCount );
280 # First, subtract the overhead!
281 $overheadTotal = $overheadMemory = $overheadInternal = array();
282 foreach( $this->mStack
as $entry ){
286 $elapsed = $end - $start;
287 $memory = $entry[5] - $entry[3];
289 if( $fname == '-overhead-total' ){
290 $overheadTotal[] = $elapsed;
291 $overheadMemory[] = $memory;
293 elseif( $fname == '-overhead-internal' ){
294 $overheadInternal[] = $elapsed;
297 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
298 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
299 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
302 foreach( $this->mStack
as $index => $entry ){
306 $elapsed = $end - $start;
308 $memory = $entry[5] - $entry[3];
309 $subcalls = $this->calltreeCount( $this->mStack
, $index );
311 if( !preg_match( '/^-overhead/', $fname ) ){
312 # Adjust for profiling overhead (except special values with elapsed=0
314 $elapsed -= $overheadInternal;
315 $elapsed -= ($subcalls * $overheadTotal);
316 $memory -= ($subcalls * $overheadMemory);
320 if( !array_key_exists( $fname, $this->mCollated
) ){
321 $this->mCollated
[$fname] = 0;
322 $this->mCalls
[$fname] = 0;
323 $this->mMemory
[$fname] = 0;
324 $this->mMin
[$fname] = 1 << 24;
325 $this->mMax
[$fname] = 0;
326 $this->mOverhead
[$fname] = 0;
329 $this->mCollated
[$fname] +
= $elapsed;
330 $this->mCalls
[$fname]++
;
331 $this->mMemory
[$fname] +
= $memory;
332 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
333 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
334 $this->mOverhead
[$fname] +
= $subcalls;
337 $total = @$this->mCollated
['-total'];
338 $this->mCalls
['-overhead-total'] = $profileCount;
341 arsort( $this->mCollated
, SORT_NUMERIC
);
342 foreach( $this->mCollated
as $fname => $elapsed ){
343 $calls = $this->mCalls
[$fname];
344 $percent = $total ?
100. * $elapsed / $total : 0;
345 $memory = $this->mMemory
[$fname];
346 $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]);
348 if( $wgProfileToDatabase ) {
349 self
::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
352 $prof .= "\nTotal: $total\n\n";
358 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
360 protected static function calculateOverhead( $profileCount ) {
361 wfProfileIn( '-overhead-total' );
362 for( $i = 0; $i < $profileCount; $i++
){
363 wfProfileIn( '-overhead-internal' );
364 wfProfileOut( '-overhead-internal' );
366 wfProfileOut( '-overhead-total' );
370 * Counts the number of profiled function calls sitting under
371 * the given point in the call graph. Not the most efficient algo.
373 * @param $stack Array:
374 * @param $start Integer:
378 function calltreeCount($stack, $start) {
379 $level = $stack[$start][1];
381 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
388 * Log a function into the database.
390 * @param $name String: function name
391 * @param $timeSum Float
392 * @param $eventCount Integer: number of times that function was called
393 * @param $memorySum Integer: memory used by the function
395 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
396 # Do not log anything if database is readonly (bug 5375)
397 if( wfReadOnly() ) { return; }
399 global $wgProfilePerHost;
401 $dbw = wfGetDB( DB_MASTER
);
402 if( !is_object( $dbw ) )
404 $errorState = $dbw->ignoreErrors( true );
406 $name = substr($name, 0, 255);
408 if( $wgProfilePerHost ){
409 $pfhost = wfHostname();
415 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
416 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
418 $dbw->update( 'profiling',
420 "pf_count=pf_count+{$eventCount}",
421 "pf_time=pf_time+{$timeSum}",
422 "pf_memory=pf_memory+{$memorySum}",
426 'pf_server' => $pfhost,
431 $rc = $dbw->affectedRows();
433 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
434 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
435 __METHOD__
, array ('IGNORE'));
437 // When we upgrade to mysql 4.1, the insert+update
438 // can be merged into just a insert with this construct added:
439 // "ON DUPLICATE KEY UPDATE ".
440 // "pf_count=pf_count + VALUES(pf_count), ".
441 // "pf_time=pf_time + VALUES(pf_time)";
442 $dbw->ignoreErrors( $errorState );
446 * Get the function name of the current profiling section
448 function getCurrentSection() {
449 $elt = end( $this->mWorkStack
);
454 * Get function caller
456 * @param $level Integer
458 static function getCaller( $level ) {
459 $backtrace = wfDebugBacktrace();
460 if ( isset( $backtrace[$level] ) ) {
461 if ( isset( $backtrace[$level]['class'] ) ) {
462 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
464 $caller = $backtrace[$level]['function'];
473 * Add an entry in the debug log file
475 * @param $s String to output
477 function debug( $s ) {
478 if( function_exists( 'wfDebug' ) ) {