ce2e5323ecd92e52d03b0e08eb34bb2256c23a16
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
34 function wfGetProfilingOutput() {
36 return $wgProfiler->getOutput();
40 * Close opened profiling sections
42 function wfProfileClose() {
47 if (!function_exists('memory_get_usage')) {
48 # Old PHP or --enable-memory-limit not compiled in
49 function memory_get_usage() {
59 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
60 var $mCalls = array (), $mTotals = array ();
61 var $mTemplated = false;
63 function __construct() {
64 // Push an entry for the pre-profile setup time onto the stack
65 global $wgRequestTime;
66 if ( !empty( $wgRequestTime ) ) {
67 $this->mWorkStack
[] = array( '-total', 0, $wgRequestTime, 0 );
68 $this->mStack
[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
70 $this->profileIn( '-total' );
75 * Called by wfProfieIn()
77 * @param $functionname String
79 public function profileIn( $functionname ) {
80 global $wgDebugFunctionEntry, $wgProfiling;
81 if( !$wgProfiling ) return;
82 if( $wgDebugFunctionEntry ){
83 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
86 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
90 * Called by wfProfieOut()
92 * @param $functionname String
94 public function profileOut($functionname) {
95 global $wgDebugFunctionEntry, $wgProfiling;
96 if( !$wgProfiling ) return;
97 $memory = memory_get_usage();
98 $time = $this->getTime();
100 if( $wgDebugFunctionEntry ){
101 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
104 $bit = array_pop($this->mWorkStack
);
107 $this->debug("Profiling error, !\$bit: $functionname\n");
109 //if( $wgDebugProfiling ){
110 if( $functionname == 'close' ){
111 $message = "Profile section ended by close(): {$bit[0]}";
112 $this->debug( "$message\n" );
113 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
115 elseif( $bit[0] != $functionname ){
116 $message = "Profiling error: in({$bit[0]}), out($functionname)";
117 $this->debug( "$message\n" );
118 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
123 $this->mStack
[] = $bit;
128 * called by wfProfileClose()
130 public function close() {
133 # Avoid infinite loop
137 while( count( $this->mWorkStack
) ){
138 $this->profileOut( 'close' );
143 * Mark this call as templated or not
147 function setTemplated( $t ) {
148 $this->mTemplated
= $t;
152 * Called by wfGetProfilingOutput()
154 public function getOutput() {
155 global $wgDebugFunctionEntry, $wgProfileCallTree;
156 $wgDebugFunctionEntry = false;
158 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
159 return "No profiling output\n";
163 if( $wgProfileCallTree ) {
164 global $wgProfileToDatabase;
165 # XXX: We must call $this->getFunctionReport() to log to the DB
166 if( $wgProfileToDatabase ) {
167 $this->getFunctionReport();
169 return $this->getCallTree();
171 return $this->getFunctionReport();
176 * Returns a tree of function call instead of a list of functions
178 function getCallTree() {
179 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
183 * Recursive function the format the current profiling array into a tree
185 * @param $stack profiling array
187 function remapCallTree( $stack ) {
188 if( count( $stack ) < 2 ){
192 for( $max = count( $stack ) - 1; $max > 0; ){
193 /* Find all items under this entry */
194 $level = $stack[$max][1];
196 for( $i = $max -1; $i >= 0; $i-- ){
197 if( $stack[$i][1] > $level ){
198 $working[] = $stack[$i];
203 $working = $this->remapCallTree( array_reverse( $working ) );
205 foreach( $working as $item ){
206 array_push( $output, $item );
208 array_unshift( $output, $stack[$max] );
211 array_unshift( $outputs, $output );
214 foreach( $outputs as $output ){
215 foreach( $output as $item ){
223 * Callback to get a formatted line for the call tree
225 function getCallTreeLine( $entry ) {
226 list( $fname, $level, $start, /* $x */, $end) = $entry;
227 $delta = $end - $start;
228 $space = str_repeat(' ', $level);
229 # The ugly double sprintf is to work around a PHP bug,
230 # which has been fixed in recent releases.
231 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
235 return microtime(true);
236 #return $this->getUserTime();
239 function getUserTime() {
241 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6
;
245 * Returns a list of profiled functions.
246 * Also log it into the database if $wgProfileToDatabase is set to true.
248 function getFunctionReport() {
249 global $wgProfileToDatabase;
252 $nameWidth = $width - 65;
253 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
254 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
255 $prof = "\nProfiling data\n";
256 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
257 $this->mCollated
= array ();
258 $this->mCalls
= array ();
259 $this->mMemory
= array ();
261 # Estimate profiling overhead
262 $profileCount = count($this->mStack
);
263 self
::calculateOverhead( $profileCount );
265 # First, subtract the overhead!
266 $overheadTotal = $overheadMemory = $overheadInternal = array();
267 foreach( $this->mStack
as $entry ){
271 $elapsed = $end - $start;
272 $memory = $entry[5] - $entry[3];
274 if( $fname == '-overhead-total' ){
275 $overheadTotal[] = $elapsed;
276 $overheadMemory[] = $memory;
278 elseif( $fname == '-overhead-internal' ){
279 $overheadInternal[] = $elapsed;
282 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
283 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
284 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
287 foreach( $this->mStack
as $index => $entry ){
291 $elapsed = $end - $start;
293 $memory = $entry[5] - $entry[3];
294 $subcalls = $this->calltreeCount( $this->mStack
, $index );
296 if( !preg_match( '/^-overhead/', $fname ) ){
297 # Adjust for profiling overhead (except special values with elapsed=0
299 $elapsed -= $overheadInternal;
300 $elapsed -= ($subcalls * $overheadTotal);
301 $memory -= ($subcalls * $overheadMemory);
305 if( !array_key_exists( $fname, $this->mCollated
) ){
306 $this->mCollated
[$fname] = 0;
307 $this->mCalls
[$fname] = 0;
308 $this->mMemory
[$fname] = 0;
309 $this->mMin
[$fname] = 1 << 24;
310 $this->mMax
[$fname] = 0;
311 $this->mOverhead
[$fname] = 0;
314 $this->mCollated
[$fname] +
= $elapsed;
315 $this->mCalls
[$fname]++
;
316 $this->mMemory
[$fname] +
= $memory;
317 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
318 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
319 $this->mOverhead
[$fname] +
= $subcalls;
322 $total = @$this->mCollated
['-total'];
323 $this->mCalls
['-overhead-total'] = $profileCount;
326 arsort( $this->mCollated
, SORT_NUMERIC
);
327 foreach( $this->mCollated
as $fname => $elapsed ){
328 $calls = $this->mCalls
[$fname];
329 $percent = $total ?
100. * $elapsed / $total : 0;
330 $memory = $this->mMemory
[$fname];
331 $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]);
333 if( $wgProfileToDatabase ) {
334 self
::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
337 $prof .= "\nTotal: $total\n\n";
343 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
345 protected static function calculateOverhead( $profileCount ) {
346 wfProfileIn( '-overhead-total' );
347 for( $i = 0; $i < $profileCount; $i++
){
348 wfProfileIn( '-overhead-internal' );
349 wfProfileOut( '-overhead-internal' );
351 wfProfileOut( '-overhead-total' );
355 * Counts the number of profiled function calls sitting under
356 * the given point in the call graph. Not the most efficient algo.
358 * @param $stack Array:
359 * @param $start Integer:
363 function calltreeCount($stack, $start) {
364 $level = $stack[$start][1];
366 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
373 * Log a function into the database.
375 * @param $name String: function name
376 * @param $timeSum Float
377 * @param $eventCount Integer: number of times that function was called
378 * @param $memorySum Integer: memory used by the function
380 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
381 # Do not log anything if database is readonly (bug 5375)
382 if( wfReadOnly() ) { return; }
384 global $wgProfilePerHost;
386 $dbw = wfGetDB( DB_MASTER
);
387 if( !is_object( $dbw ) )
389 $errorState = $dbw->ignoreErrors( true );
391 $name = substr($name, 0, 255);
393 if( $wgProfilePerHost ){
394 $pfhost = wfHostname();
400 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
401 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
403 $dbw->update( 'profiling',
405 "pf_count=pf_count+{$eventCount}",
406 "pf_time=pf_time+{$timeSum}",
407 "pf_memory=pf_memory+{$memorySum}",
411 'pf_server' => $pfhost,
416 $rc = $dbw->affectedRows();
418 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
419 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
420 __METHOD__
, array ('IGNORE'));
422 // When we upgrade to mysql 4.1, the insert+update
423 // can be merged into just a insert with this construct added:
424 // "ON DUPLICATE KEY UPDATE ".
425 // "pf_count=pf_count + VALUES(pf_count), ".
426 // "pf_time=pf_time + VALUES(pf_time)";
427 $dbw->ignoreErrors( $errorState );
431 * Get the function name of the current profiling section
433 function getCurrentSection() {
434 $elt = end( $this->mWorkStack
);
439 * Get function caller
441 * @param $level Integer
443 static function getCaller( $level ) {
444 $backtrace = wfDebugBacktrace();
445 if ( isset( $backtrace[$level] ) ) {
446 if ( isset( $backtrace[$level]['class'] ) ) {
447 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
449 $caller = $backtrace[$level]['function'];
458 * Add an entry in the debug log file
460 * @param $s String to output
462 function debug( $s ) {
463 if( function_exists( 'wfDebug' ) ) {