Fixes for r81936 per Tim's review
[mediawiki.git] / includes / Profiler.php
blob551ce233cea14f46534c1216e00cd843b0e253e3
1 <?php
2 /**
3 * @defgroup Profiler Profiler
5 * @file
6 * @ingroup Profiler
7 * This file is only included if profiling is enabled
8 */
10 /** backward compatibility */
11 $wgProfiling = true;
13 /**
14 * Begin profiling of a function
15 * @param $functionname String: name of the function we will profile
17 function wfProfileIn( $functionname ) {
18 global $wgProfiler;
19 $wgProfiler->profileIn( $functionname );
22 /**
23 * Stop profiling of a function
24 * @param $functionname String: name of the function we have profiled
26 function wfProfileOut( $functionname = 'missing' ) {
27 global $wgProfiler;
28 $wgProfiler->profileOut( $functionname );
31 /**
32 * Returns a profiling output to be stored in debug file
34 * @param $start Float
35 * @param $elapsed Float: time elapsed since the beginning of the request
37 function wfGetProfilingOutput( $start, $elapsed ) {
38 global $wgProfiler;
39 return $wgProfiler->getOutput( $start, $elapsed );
42 /**
43 * Close opened profiling sections
45 function wfProfileClose() {
46 global $wgProfiler;
47 $wgProfiler->close();
50 if (!function_exists('memory_get_usage')) {
51 # Old PHP or --enable-memory-limit not compiled in
52 function memory_get_usage() {
53 return 0;
57 /**
58 * @ingroup Profiler
59 * @todo document
61 class Profiler {
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 );
72 } else {
73 $this->profileIn( '-total' );
77 /**
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() );
92 /**
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);
109 if (!$bit) {
110 $this->debug("Profiling error, !\$bit: $functionname\n");
111 } else {
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 );
124 $bit[] = $time;
125 $bit[] = $memory;
126 $this->mStack[] = $bit;
131 * called by wfProfileClose()
133 function close() {
134 global $wgProfiling;
136 # Avoid infinite loop
137 if( !$wgProfiling )
138 return;
140 while( count( $this->mWorkStack ) ){
141 $this->profileOut( 'close' );
146 * Mark this call as templated or not
148 * @param $t Boolean
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";
164 $this->close();
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();
173 } else {
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 ){
192 return $stack;
194 $outputs = array ();
195 for( $max = count( $stack ) - 1; $max > 0; ){
196 /* Find all items under this entry */
197 $level = $stack[$max][1];
198 $working = array ();
199 for( $i = $max -1; $i >= 0; $i-- ){
200 if( $stack[$i][1] > $level ){
201 $working[] = $stack[$i];
202 } else {
203 break;
206 $working = $this->remapCallTree( array_reverse( $working ) );
207 $output = array();
208 foreach( $working as $item ){
209 array_push( $output, $item );
211 array_unshift( $output, $stack[$max] );
212 $max = $i;
214 array_unshift( $outputs, $output );
216 $final = array();
217 foreach( $outputs as $output ){
218 foreach( $output as $item ){
219 $final[] = $item;
222 return $final;
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 );
237 function getTime() {
238 return microtime(true);
239 #return $this->getUserTime();
242 function getUserTime() {
243 $ru = getrusage();
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;
254 $width = 140;
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 self::calculateOverhead( $profileCount );
268 # First, subtract the overhead!
269 $overheadTotal = $overheadMemory = $overheadInternal = array();
270 foreach( $this->mStack as $entry ){
271 $fname = $entry[0];
272 $start = $entry[2];
273 $end = $entry[4];
274 $elapsed = $end - $start;
275 $memory = $entry[5] - $entry[3];
277 if( $fname == '-overhead-total' ){
278 $overheadTotal[] = $elapsed;
279 $overheadMemory[] = $memory;
281 elseif( $fname == '-overhead-internal' ){
282 $overheadInternal[] = $elapsed;
285 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
286 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
287 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
289 # Collate
290 foreach( $this->mStack as $index => $entry ){
291 $fname = $entry[0];
292 $start = $entry[2];
293 $end = $entry[4];
294 $elapsed = $end - $start;
296 $memory = $entry[5] - $entry[3];
297 $subcalls = $this->calltreeCount( $this->mStack, $index );
299 if( !preg_match( '/^-overhead/', $fname ) ){
300 # Adjust for profiling overhead (except special values with elapsed=0
301 if( $elapsed ) {
302 $elapsed -= $overheadInternal;
303 $elapsed -= ($subcalls * $overheadTotal);
304 $memory -= ($subcalls * $overheadMemory);
308 if( !array_key_exists( $fname, $this->mCollated ) ){
309 $this->mCollated[$fname] = 0;
310 $this->mCalls[$fname] = 0;
311 $this->mMemory[$fname] = 0;
312 $this->mMin[$fname] = 1 << 24;
313 $this->mMax[$fname] = 0;
314 $this->mOverhead[$fname] = 0;
317 $this->mCollated[$fname] += $elapsed;
318 $this->mCalls[$fname]++;
319 $this->mMemory[$fname] += $memory;
320 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
321 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
322 $this->mOverhead[$fname] += $subcalls;
325 $total = @$this->mCollated['-total'];
326 $this->mCalls['-overhead-total'] = $profileCount;
328 # Output
329 arsort( $this->mCollated, SORT_NUMERIC );
330 foreach( $this->mCollated as $fname => $elapsed ){
331 $calls = $this->mCalls[$fname];
332 $percent = $total ? 100. * $elapsed / $total : 0;
333 $memory = $this->mMemory[$fname];
334 $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]);
335 # Log to the DB
336 if( $wgProfileToDatabase ) {
337 self::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
340 $prof .= "\nTotal: $total\n\n";
342 return $prof;
346 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
348 protected static function calculateOverhead( $profileCount ) {
349 wfProfileIn( '-overhead-total' );
350 for( $i = 0; $i < $profileCount; $i++ ){
351 wfProfileIn( '-overhead-internal' );
352 wfProfileOut( '-overhead-internal' );
354 wfProfileOut( '-overhead-total' );
358 * Counts the number of profiled function calls sitting under
359 * the given point in the call graph. Not the most efficient algo.
361 * @param $stack Array:
362 * @param $start Integer:
363 * @return Integer
364 * @private
366 function calltreeCount($stack, $start) {
367 $level = $stack[$start][1];
368 $count = 0;
369 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
370 $count ++;
372 return $count;
376 * Log a function into the database.
378 * @param $name String: function name
379 * @param $timeSum Float
380 * @param $eventCount Integer: number of times that function was called
381 * @param $memorySum Integer: memory used by the function
383 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
384 # Do not log anything if database is readonly (bug 5375)
385 if( wfReadOnly() ) { return; }
387 global $wgProfilePerHost;
389 $dbw = wfGetDB( DB_MASTER );
390 if( !is_object( $dbw ) )
391 return false;
392 $errorState = $dbw->ignoreErrors( true );
394 $name = substr($name, 0, 255);
396 if( $wgProfilePerHost ){
397 $pfhost = wfHostname();
398 } else {
399 $pfhost = '';
402 // Kludge
403 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
404 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
406 $dbw->update( 'profiling',
407 array(
408 "pf_count=pf_count+{$eventCount}",
409 "pf_time=pf_time+{$timeSum}",
410 "pf_memory=pf_memory+{$memorySum}",
412 array(
413 'pf_name' => $name,
414 'pf_server' => $pfhost,
416 __METHOD__ );
419 $rc = $dbw->affectedRows();
420 if ($rc == 0) {
421 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
422 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
423 __METHOD__, array ('IGNORE'));
425 // When we upgrade to mysql 4.1, the insert+update
426 // can be merged into just a insert with this construct added:
427 // "ON DUPLICATE KEY UPDATE ".
428 // "pf_count=pf_count + VALUES(pf_count), ".
429 // "pf_time=pf_time + VALUES(pf_time)";
430 $dbw->ignoreErrors( $errorState );
434 * Get the function name of the current profiling section
436 function getCurrentSection() {
437 $elt = end( $this->mWorkStack );
438 return $elt[0];
442 * Get function caller
444 * @param $level Integer
446 static function getCaller( $level ) {
447 $backtrace = wfDebugBacktrace();
448 if ( isset( $backtrace[$level] ) ) {
449 if ( isset( $backtrace[$level]['class'] ) ) {
450 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
451 } else {
452 $caller = $backtrace[$level]['function'];
454 } else {
455 $caller = 'unknown';
457 return $caller;
461 * Add an entry in the debug log file
463 * @param $s String to output
465 function debug( $s ) {
466 if( function_exists( 'wfDebug' ) ) {
467 wfDebug( $s );