3 * @defgroup Profiler Profiler
7 * This file is only included if profiling is enabled
10 /** backward compatibility */
14 * Begin profiling of a function
15 * @param $functionname String: name of the function we will profile
17 function wfProfileIn( $functionname ) {
19 $wgProfiler->profileIn( $functionname );
23 * Stop profiling of a function
24 * @param $functionname String: name of the function we have profiled
26 function wfProfileOut( $functionname = 'missing' ) {
28 $wgProfiler->profileOut( $functionname );
32 * Returns a profiling output to be stored in debug file
35 * @param $elapsed Float: time elapsed since the beginning of the request
37 function wfGetProfilingOutput( $start, $elapsed ) {
39 return $wgProfiler->getOutput( $start, $elapsed );
43 * Close opened profiling sections
45 function wfProfileClose() {
50 if (!function_exists('memory_get_usage')) {
51 # Old PHP or --enable-memory-limit not compiled in
52 function memory_get_usage() {
62 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
63 var $mCalls = array (), $mTotals = array ();
64 var $mTemplated = false;
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' );
78 * Called by wfProfieIn()
80 * @param $functionname String
82 function profileIn( $functionname ) {
83 global $wgDebugFunctionEntry, $wgProfiling;
84 if( !$wgProfiling ) return;
85 if( $wgDebugFunctionEntry ){
86 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
89 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
93 * Called by wfProfieOut()
95 * @param $functionname String
97 function profileOut($functionname) {
98 global $wgDebugFunctionEntry, $wgProfiling;
99 if( !$wgProfiling ) return;
100 $memory = memory_get_usage();
101 $time = $this->getTime();
103 if( $wgDebugFunctionEntry ){
104 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
107 $bit = array_pop($this->mWorkStack
);
110 $this->debug("Profiling error, !\$bit: $functionname\n");
112 //if( $wgDebugProfiling ){
113 if( $functionname == 'close' ){
114 $message = "Profile section ended by close(): {$bit[0]}";
115 $this->debug( "$message\n" );
116 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
118 elseif( $bit[0] != $functionname ){
119 $message = "Profiling error: in({$bit[0]}), out($functionname)";
120 $this->debug( "$message\n" );
121 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
126 $this->mStack
[] = $bit;
131 * called by wfProfileClose()
136 # Avoid infinite loop
140 while( count( $this->mWorkStack
) ){
141 $this->profileOut( 'close' );
146 * Mark this call as templated or not
150 function setTemplated( $t ) {
151 $this->mTemplated
= $t;
155 * Called by wfGetProfilingOutput()
157 function getOutput() {
158 global $wgDebugFunctionEntry, $wgProfileCallTree;
159 $wgDebugFunctionEntry = false;
161 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
162 return "No profiling output\n";
166 if( $wgProfileCallTree ) {
167 global $wgProfileToDatabase;
168 # XXX: We must call $this->getFunctionReport() to log to the DB
169 if( $wgProfileToDatabase ) {
170 $this->getFunctionReport();
172 return $this->getCallTree();
174 return $this->getFunctionReport();
179 * Returns a tree of function call instead of a list of functions
181 function getCallTree() {
182 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
186 * Recursive function the format the current profiling array into a tree
188 * @param $stack profiling array
190 function remapCallTree( $stack ) {
191 if( count( $stack ) < 2 ){
195 for( $max = count( $stack ) - 1; $max > 0; ){
196 /* Find all items under this entry */
197 $level = $stack[$max][1];
199 for( $i = $max -1; $i >= 0; $i-- ){
200 if( $stack[$i][1] > $level ){
201 $working[] = $stack[$i];
206 $working = $this->remapCallTree( array_reverse( $working ) );
208 foreach( $working as $item ){
209 array_push( $output, $item );
211 array_unshift( $output, $stack[$max] );
214 array_unshift( $outputs, $output );
217 foreach( $outputs as $output ){
218 foreach( $output as $item ){
226 * Callback to get a formatted line for the call tree
228 function getCallTreeLine( $entry ) {
229 list( $fname, $level, $start, /* $x */, $end) = $entry;
230 $delta = $end - $start;
231 $space = str_repeat(' ', $level);
232 # The ugly double sprintf is to work around a PHP bug,
233 # which has been fixed in recent releases.
234 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
238 return microtime(true);
239 #return $this->getUserTime();
242 function getUserTime() {
244 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6
;
248 * Returns a list of profiled functions.
249 * Also log it into the database if $wgProfileToDatabase is set to true.
251 function getFunctionReport() {
252 global $wgProfileToDatabase;
255 $nameWidth = $width - 65;
256 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
257 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
258 $prof = "\nProfiling data\n";
259 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
260 $this->mCollated
= array ();
261 $this->mCalls
= array ();
262 $this->mMemory
= array ();
264 # Estimate profiling overhead
265 $profileCount = count($this->mStack
);
266 wfProfileIn( '-overhead-total' );
267 for( $i = 0; $i < $profileCount; $i ++
){
268 wfProfileIn( '-overhead-internal' );
269 wfProfileOut( '-overhead-internal' );
271 wfProfileOut( '-overhead-total' );
273 # First, subtract the overhead!
274 $overheadTotal = $overheadMemory = $overheadInternal = array();
275 foreach( $this->mStack
as $entry ){
279 $elapsed = $end - $start;
280 $memory = $entry[5] - $entry[3];
282 if( $fname == '-overhead-total' ){
283 $overheadTotal[] = $elapsed;
284 $overheadMemory[] = $memory;
286 elseif( $fname == '-overhead-internal' ){
287 $overheadInternal[] = $elapsed;
290 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
291 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
292 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
295 foreach( $this->mStack
as $index => $entry ){
299 $elapsed = $end - $start;
301 $memory = $entry[5] - $entry[3];
302 $subcalls = $this->calltreeCount( $this->mStack
, $index );
304 if( !preg_match( '/^-overhead/', $fname ) ){
305 # Adjust for profiling overhead (except special values with elapsed=0
307 $elapsed -= $overheadInternal;
308 $elapsed -= ($subcalls * $overheadTotal);
309 $memory -= ($subcalls * $overheadMemory);
313 if( !array_key_exists( $fname, $this->mCollated
) ){
314 $this->mCollated
[$fname] = 0;
315 $this->mCalls
[$fname] = 0;
316 $this->mMemory
[$fname] = 0;
317 $this->mMin
[$fname] = 1 << 24;
318 $this->mMax
[$fname] = 0;
319 $this->mOverhead
[$fname] = 0;
322 $this->mCollated
[$fname] +
= $elapsed;
323 $this->mCalls
[$fname]++
;
324 $this->mMemory
[$fname] +
= $memory;
325 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
326 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
327 $this->mOverhead
[$fname] +
= $subcalls;
330 $total = @$this->mCollated
['-total'];
331 $this->mCalls
['-overhead-total'] = $profileCount;
334 arsort( $this->mCollated
, SORT_NUMERIC
);
335 foreach( $this->mCollated
as $fname => $elapsed ){
336 $calls = $this->mCalls
[$fname];
337 $percent = $total ?
100. * $elapsed / $total : 0;
338 $memory = $this->mMemory
[$fname];
339 $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]);
341 if( $wgProfileToDatabase ) {
342 self
::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
345 $prof .= "\nTotal: $total\n\n";
351 * Counts the number of profiled function calls sitting under
352 * the given point in the call graph. Not the most efficient algo.
354 * @param $stack Array:
355 * @param $start Integer:
359 function calltreeCount($stack, $start) {
360 $level = $stack[$start][1];
362 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
369 * Log a function into the database.
371 * @param $name String: function name
372 * @param $timeSum Float
373 * @param $eventCount Integer: number of times that function was called
374 * @param $memorySum Integer: memory used by the function
376 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
377 # Do not log anything if database is readonly (bug 5375)
378 if( wfReadOnly() ) { return; }
380 global $wgProfilePerHost;
382 $dbw = wfGetDB( DB_MASTER
);
383 if( !is_object( $dbw ) )
385 $errorState = $dbw->ignoreErrors( true );
387 $name = substr($name, 0, 255);
389 if( $wgProfilePerHost ){
390 $pfhost = wfHostname();
396 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
397 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
399 $dbw->update( 'profiling',
401 "pf_count=pf_count+{$eventCount}",
402 "pf_time=pf_time+{$timeSum}",
403 "pf_memory=pf_memory+{$memorySum}",
407 'pf_server' => $pfhost,
412 $rc = $dbw->affectedRows();
414 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
415 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
416 __METHOD__
, array ('IGNORE'));
418 // When we upgrade to mysql 4.1, the insert+update
419 // can be merged into just a insert with this construct added:
420 // "ON DUPLICATE KEY UPDATE ".
421 // "pf_count=pf_count + VALUES(pf_count), ".
422 // "pf_time=pf_time + VALUES(pf_time)";
423 $dbw->ignoreErrors( $errorState );
427 * Get the function name of the current profiling section
429 function getCurrentSection() {
430 $elt = end( $this->mWorkStack
);
435 * Get function caller
437 * @param $level Integer
439 static function getCaller( $level ) {
440 $backtrace = wfDebugBacktrace();
441 if ( isset( $backtrace[$level] ) ) {
442 if ( isset( $backtrace[$level]['class'] ) ) {
443 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
445 $caller = $backtrace[$level]['function'];
454 * Add an entry in the debug log file
456 * @param $s String to output
458 function debug( $s ) {
459 if( function_exists( 'wfDebug' ) ) {