Fix for r38784: force the noconvertlink toggle to be marked as used, otherwise it...
[mediawiki.git] / includes / Profiler.php
blobcef89dd355c2a9088f74b001a274ab9a8cb965cb
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 $functioname 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 $functioname 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 float $start
35 * @param float $elapsed 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 ();
65 function __construct() {
66 // Push an entry for the pre-profile setup time onto the stack
67 global $wgRequestTime;
68 if ( !empty( $wgRequestTime ) ) {
69 $this->mWorkStack[] = array( '-total', 0, $wgRequestTime, 0 );
70 $this->mStack[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
71 } else {
72 $this->profileIn( '-total' );
76 /**
77 * Called by wfProfieIn()
78 * @param $functionname string
80 function profileIn( $functionname ) {
81 global $wgDebugFunctionEntry;
83 if( $wgDebugFunctionEntry ){
84 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
87 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
90 /**
91 * Called by wfProfieOut()
92 * @param $functionname string
94 function profileOut($functionname) {
95 global $wgDebugFunctionEntry;
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);
106 if (!$bit) {
107 $this->debug("Profiling error, !\$bit: $functionname\n");
108 } else {
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 );
121 $bit[] = $time;
122 $bit[] = $memory;
123 $this->mStack[] = $bit;
128 * called by wfProfileClose()
130 function close() {
131 while( count( $this->mWorkStack ) ){
132 $this->profileOut( 'close' );
137 * called by wfGetProfilingOutput()
139 function getOutput() {
140 global $wgDebugFunctionEntry, $wgProfileCallTree;
141 $wgDebugFunctionEntry = false;
143 if( !count( $this->mStack ) && !count( $this->mCollated ) ){
144 return "No profiling output\n";
146 $this->close();
148 if( $wgProfileCallTree ){
149 return $this->getCallTree();
150 } else {
151 return $this->getFunctionReport();
156 * returns a tree of function call instead of a list of functions
158 function getCallTree() {
159 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
163 * Recursive function the format the current profiling array into a tree
165 * @param $stack profiling array
167 function remapCallTree( $stack ) {
168 if( count( $stack ) < 2 ){
169 return $stack;
171 $outputs = array ();
172 for( $max = count( $stack ) - 1; $max > 0; ){
173 /* Find all items under this entry */
174 $level = $stack[$max][1];
175 $working = array ();
176 for( $i = $max -1; $i >= 0; $i-- ){
177 if( $stack[$i][1] > $level ){
178 $working[] = $stack[$i];
179 } else {
180 break;
183 $working = $this->remapCallTree( array_reverse( $working ) );
184 $output = array();
185 foreach( $working as $item ){
186 array_push( $output, $item );
188 array_unshift( $output, $stack[$max] );
189 $max = $i;
191 array_unshift( $outputs, $output );
193 $final = array();
194 foreach( $outputs as $output ){
195 foreach( $output as $item ){
196 $final[] = $item;
199 return $final;
203 * Callback to get a formatted line for the call tree
205 function getCallTreeLine($entry) {
206 list( $fname, $level, $start, /* $x */, $end) = $entry;
207 $delta = $end - $start;
208 $space = str_repeat(' ', $level);
210 # The ugly double sprintf is to work around a PHP bug,
211 # which has been fixed in recent releases.
212 return sprintf( "%10s %s %s\n",
213 trim( sprintf( "%7.3f", $delta * 1000.0 ) ),
214 $space, $fname );
217 function getTime() {
218 return microtime(true);
219 #return $this->getUserTime();
222 function getUserTime() {
223 $ru = getrusage();
224 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6;
228 * Returns a list of profiled functions.
229 * Also log it into the database if $wgProfileToDatabase is set to true.
231 function getFunctionReport() {
232 global $wgProfileToDatabase;
234 $width = 140;
235 $nameWidth = $width - 65;
236 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
237 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
238 $prof = "\nProfiling data\n";
239 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
240 $this->mCollated = array ();
241 $this->mCalls = array ();
242 $this->mMemory = array ();
244 # Estimate profiling overhead
245 $profileCount = count($this->mStack);
246 wfProfileIn( '-overhead-total' );
247 for( $i = 0; $i < $profileCount; $i ++ ){
248 wfProfileIn( '-overhead-internal' );
249 wfProfileOut( '-overhead-internal' );
251 wfProfileOut( '-overhead-total' );
253 # First, subtract the overhead!
254 foreach( $this->mStack as $entry ){
255 $fname = $entry[0];
256 $start = $entry[2];
257 $end = $entry[4];
258 $elapsed = $end - $start;
259 $memory = $entry[5] - $entry[3];
261 if( $fname == '-overhead-total' ){
262 $overheadTotal[] = $elapsed;
263 $overheadMemory[] = $memory;
265 elseif( $fname == '-overhead-internal' ){
266 $overheadInternal[] = $elapsed;
269 $overheadTotal = array_sum( $overheadTotal ) / count( $overheadInternal );
270 $overheadMemory = array_sum( $overheadMemory ) / count( $overheadInternal );
271 $overheadInternal = array_sum( $overheadInternal ) / count( $overheadInternal );
273 # Collate
274 foreach( $this->mStack as $index => $entry ){
275 $fname = $entry[0];
276 $start = $entry[2];
277 $end = $entry[4];
278 $elapsed = $end - $start;
280 $memory = $entry[5] - $entry[3];
281 $subcalls = $this->calltreeCount( $this->mStack, $index );
283 if( !preg_match( '/^-overhead/', $fname ) ){
284 # Adjust for profiling overhead (except special values with elapsed=0
285 if( $elapsed ) {
286 $elapsed -= $overheadInternal;
287 $elapsed -= ($subcalls * $overheadTotal);
288 $memory -= ($subcalls * $overheadMemory);
292 if( !array_key_exists( $fname, $this->mCollated ) ){
293 $this->mCollated[$fname] = 0;
294 $this->mCalls[$fname] = 0;
295 $this->mMemory[$fname] = 0;
296 $this->mMin[$fname] = 1 << 24;
297 $this->mMax[$fname] = 0;
298 $this->mOverhead[$fname] = 0;
301 $this->mCollated[$fname] += $elapsed;
302 $this->mCalls[$fname]++;
303 $this->mMemory[$fname] += $memory;
304 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
305 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
306 $this->mOverhead[$fname] += $subcalls;
309 $total = @$this->mCollated['-total'];
310 $this->mCalls['-overhead-total'] = $profileCount;
312 # Output
313 arsort( $this->mCollated, SORT_NUMERIC );
314 foreach( $this->mCollated as $fname => $elapsed ){
315 $calls = $this->mCalls[$fname];
316 $percent = $total ? 100. * $elapsed / $total : 0;
317 $memory = $this->mMemory[$fname];
318 $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]);
320 if( $wgProfileToDatabase ){
321 self::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
324 $prof .= "\nTotal: $total\n\n";
326 return $prof;
330 * Counts the number of profiled function calls sitting under
331 * the given point in the call graph. Not the most efficient algo.
333 * @param $stack Array:
334 * @param $start Integer:
335 * @return Integer
336 * @private
338 function calltreeCount($stack, $start) {
339 $level = $stack[$start][1];
340 $count = 0;
341 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
342 $count ++;
344 return $count;
348 * Log a function into the database.
350 * @param $name string: function name
351 * @param $timeSum float
352 * @param $eventCount int: number of times that function was called
354 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
355 # Do not log anything if database is readonly (bug 5375)
356 if( wfReadOnly() ) { return; }
358 # Warning: $wguname is a live patch, it should be moved to Setup.php
359 global $wguname, $wgProfilePerHost;
361 $dbw = wfGetDB( DB_MASTER );
362 if( !is_object( $dbw ) )
363 return false;
364 $errorState = $dbw->ignoreErrors( true );
366 $name = substr($name, 0, 255);
368 if( $wgProfilePerHost ){
369 $pfhost = $wguname['nodename'];
370 } else {
371 $pfhost = '';
374 // Kludge
375 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
376 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
378 $dbw->update( 'profiling',
379 array(
380 "pf_count=pf_count+{$eventCount}",
381 "pf_time=pf_time+{$timeSum}",
382 "pf_memory=pf_memory+{$memorySum}",
384 array(
385 'pf_name' => $name,
386 'pf_server' => $pfhost,
388 __METHOD__ );
391 $rc = $dbw->affectedRows();
392 if ($rc == 0) {
393 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
394 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
395 __METHOD__, array ('IGNORE'));
397 // When we upgrade to mysql 4.1, the insert+update
398 // can be merged into just a insert with this construct added:
399 // "ON DUPLICATE KEY UPDATE ".
400 // "pf_count=pf_count + VALUES(pf_count), ".
401 // "pf_time=pf_time + VALUES(pf_time)";
402 $dbw->ignoreErrors( $errorState );
406 * Get the function name of the current profiling section
408 function getCurrentSection() {
409 $elt = end( $this->mWorkStack );
410 return $elt[0];
414 * Get function caller
415 * @param $level int
417 static function getCaller( $level ) {
418 $backtrace = wfDebugBacktrace();
419 if ( isset( $backtrace[$level] ) ) {
420 if ( isset( $backtrace[$level]['class'] ) ) {
421 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
422 } else {
423 $caller = $backtrace[$level]['function'];
425 } else {
426 $caller = 'unknown';
428 return $caller;
432 * Add an entry in the debug log file
433 * @param $s string to output
435 function debug( $s ) {
436 if( function_exists( 'wfDebug' ) ) {
437 wfDebug( $s );