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 );
40 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
41 var $mCalls = array (), $mTotals = array ();
42 var $mTemplated = false;
43 private $mCollateDone = false;
44 protected $mProfileID = false;
45 private static $__instance = null;
47 function __construct() {
48 // Push an entry for the pre-profile setup time onto the stack
49 global $wgRequestTime;
50 if ( !empty( $wgRequestTime ) ) {
51 $this->mWorkStack
[] = array( '-total', 0, $wgRequestTime, 0 );
52 $this->mStack
[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
54 $this->profileIn( '-total' );
62 public static function instance() {
63 if( is_null( self
::$__instance ) ) {
65 if( is_array( $wgProfiler ) ) {
66 $class = $wgProfiler['class'];
67 self
::$__instance = new $class( $wgProfiler );
68 } elseif( $wgProfiler instanceof Profiler
) {
69 self
::$__instance = $wgProfiler; // back-compat
71 throw new MWException( '$wgProfiler set to bogus value' );
75 return self
::$__instance;
79 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
80 * @param $p Profiler object
82 public static function setInstance( Profiler
$p ) {
83 self
::$__instance = $p;
87 * Return whether this a stub profiler
91 public function isStub() {
95 public function setProfileID( $id ) {
96 $this->mProfileID
= $id;
99 public function getProfileID() {
100 if ( $this->mProfileID
=== false ) {
103 return $this->mProfileID
;
108 * Called by wfProfieIn()
110 * @param $functionname String
112 public function profileIn( $functionname ) {
113 global $wgDebugFunctionEntry;
114 if( $wgDebugFunctionEntry ){
115 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) ) . 'Entering ' . $functionname . "\n" );
118 $this->mWorkStack
[] = array( $functionname, count( $this->mWorkStack
), $this->getTime(), memory_get_usage() );
122 * Called by wfProfieOut()
124 * @param $functionname String
126 public function profileOut( $functionname ) {
127 global $wgDebugFunctionEntry;
128 $memory = memory_get_usage();
129 $time = $this->getTime();
131 if( $wgDebugFunctionEntry ){
132 $this->debug( str_repeat( ' ', count( $this->mWorkStack
) - 1 ) . 'Exiting ' . $functionname . "\n" );
135 $bit = array_pop($this->mWorkStack
);
138 $this->debug("Profiling error, !\$bit: $functionname\n");
140 //if( $wgDebugProfiling ){
141 if( $functionname == 'close' ){
142 $message = "Profile section ended by close(): {$bit[0]}";
143 $this->debug( "$message\n" );
144 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
146 elseif( $bit[0] != $functionname ){
147 $message = "Profiling error: in({$bit[0]}), out($functionname)";
148 $this->debug( "$message\n" );
149 $this->mStack
[] = array( $message, 0, '0 0', 0, '0 0', 0 );
154 $this->mStack
[] = $bit;
159 * Close opened profiling sections
161 public function close() {
162 while( count( $this->mWorkStack
) ){
163 $this->profileOut( 'close' );
168 * Mark this call as templated or not
172 function setTemplated( $t ) {
173 $this->mTemplated
= $t;
177 * Returns a profiling output to be stored in debug file
181 public function getOutput() {
182 global $wgDebugFunctionEntry, $wgProfileCallTree;
183 $wgDebugFunctionEntry = false;
185 if( !count( $this->mStack
) && !count( $this->mCollated
) ){
186 return "No profiling output\n";
189 if( $wgProfileCallTree ) {
190 return $this->getCallTree();
192 return $this->getFunctionReport();
197 * Returns a tree of function call instead of a list of functions
199 function getCallTree() {
200 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack
) ) );
204 * Recursive function the format the current profiling array into a tree
206 * @param $stack profiling array
208 function remapCallTree( $stack ) {
209 if( count( $stack ) < 2 ){
213 for( $max = count( $stack ) - 1; $max > 0; ){
214 /* Find all items under this entry */
215 $level = $stack[$max][1];
217 for( $i = $max -1; $i >= 0; $i-- ){
218 if( $stack[$i][1] > $level ){
219 $working[] = $stack[$i];
224 $working = $this->remapCallTree( array_reverse( $working ) );
226 foreach( $working as $item ){
227 array_push( $output, $item );
229 array_unshift( $output, $stack[$max] );
232 array_unshift( $outputs, $output );
235 foreach( $outputs as $output ){
236 foreach( $output as $item ){
244 * Callback to get a formatted line for the call tree
246 function getCallTreeLine( $entry ) {
247 list( $fname, $level, $start, /* $x */, $end) = $entry;
248 $delta = $end - $start;
249 $space = str_repeat(' ', $level);
250 # The ugly double sprintf is to work around a PHP bug,
251 # which has been fixed in recent releases.
252 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
256 return microtime(true);
257 #return $this->getUserTime();
260 function getUserTime() {
262 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6
;
265 protected function collateData() {
266 if ( $this->mCollateDone
) {
269 $this->mCollateDone
= true;
273 $this->mCollated
= array();
274 $this->mCalls
= array();
275 $this->mMemory
= array();
277 # Estimate profiling overhead
278 $profileCount = count($this->mStack
);
279 self
::calculateOverhead( $profileCount );
281 # First, subtract the overhead!
282 $overheadTotal = $overheadMemory = $overheadInternal = array();
283 foreach( $this->mStack
as $entry ){
287 $elapsed = $end - $start;
288 $memory = $entry[5] - $entry[3];
290 if( $fname == '-overhead-total' ){
291 $overheadTotal[] = $elapsed;
292 $overheadMemory[] = $memory;
294 elseif( $fname == '-overhead-internal' ){
295 $overheadInternal[] = $elapsed;
298 $overheadTotal = $overheadTotal ?
array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
299 $overheadMemory = $overheadMemory ?
array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
300 $overheadInternal = $overheadInternal ?
array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
303 foreach( $this->mStack
as $index => $entry ){
307 $elapsed = $end - $start;
309 $memory = $entry[5] - $entry[3];
310 $subcalls = $this->calltreeCount( $this->mStack
, $index );
312 if( !preg_match( '/^-overhead/', $fname ) ){
313 # Adjust for profiling overhead (except special values with elapsed=0
315 $elapsed -= $overheadInternal;
316 $elapsed -= ($subcalls * $overheadTotal);
317 $memory -= ($subcalls * $overheadMemory);
321 if( !array_key_exists( $fname, $this->mCollated
) ){
322 $this->mCollated
[$fname] = 0;
323 $this->mCalls
[$fname] = 0;
324 $this->mMemory
[$fname] = 0;
325 $this->mMin
[$fname] = 1 << 24;
326 $this->mMax
[$fname] = 0;
327 $this->mOverhead
[$fname] = 0;
330 $this->mCollated
[$fname] +
= $elapsed;
331 $this->mCalls
[$fname]++
;
332 $this->mMemory
[$fname] +
= $memory;
333 $this->mMin
[$fname] = min($this->mMin
[$fname], $elapsed);
334 $this->mMax
[$fname] = max($this->mMax
[$fname], $elapsed);
335 $this->mOverhead
[$fname] +
= $subcalls;
338 $this->mCalls
['-overhead-total'] = $profileCount;
339 arsort( $this->mCollated
, SORT_NUMERIC
);
343 * Returns a list of profiled functions.
344 * Also log it into the database if $wgProfileToDatabase is set to true.
346 function getFunctionReport() {
347 $this->collateData();
350 $nameWidth = $width - 65;
351 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
352 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
353 $prof = "\nProfiling data\n";
354 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
356 $total = @$this->mCollated
['-total'];
358 foreach( $this->mCollated
as $fname => $elapsed ){
359 $calls = $this->mCalls
[$fname];
360 $percent = $total ?
100. * $elapsed / $total : 0;
361 $memory = $this->mMemory
[$fname];
362 $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]);
364 $prof .= "\nTotal: $total\n\n";
370 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
372 protected static function calculateOverhead( $profileCount ) {
373 wfProfileIn( '-overhead-total' );
374 for( $i = 0; $i < $profileCount; $i++
){
375 wfProfileIn( '-overhead-internal' );
376 wfProfileOut( '-overhead-internal' );
378 wfProfileOut( '-overhead-total' );
382 * Counts the number of profiled function calls sitting under
383 * the given point in the call graph. Not the most efficient algo.
385 * @param $stack Array:
386 * @param $start Integer:
390 function calltreeCount($stack, $start) {
391 $level = $stack[$start][1];
393 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
400 * Log the whole profiling data into the database.
402 public function logData(){
403 global $wgProfilePerHost, $wgProfileToDatabase;
405 # Do not log anything if database is readonly (bug 5375)
406 if( wfReadOnly() ||
!$wgProfileToDatabase ) {
410 $dbw = wfGetDB( DB_MASTER
);
411 if( !is_object( $dbw ) ) {
415 $errorState = $dbw->ignoreErrors( true );
417 if( $wgProfilePerHost ){
418 $pfhost = wfHostname();
423 $this->collateData();
425 foreach( $this->mCollated
as $name => $elapsed ){
426 $eventCount = $this->mCalls
[$name];
427 $timeSum = (float) ($elapsed * 1000);
428 $memorySum = (float)$this->mMemory
[$name];
429 $name = substr($name, 0, 255);
432 $timeSum = ($timeSum >= 0) ?
$timeSum : 0;
433 $memorySum = ($memorySum >= 0) ?
$memorySum : 0;
435 $dbw->update( 'profiling',
437 "pf_count=pf_count+{$eventCount}",
438 "pf_time=pf_time+{$timeSum}",
439 "pf_memory=pf_memory+{$memorySum}",
443 'pf_server' => $pfhost,
447 $rc = $dbw->affectedRows();
449 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
450 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
451 __METHOD__
, array ('IGNORE'));
453 // When we upgrade to mysql 4.1, the insert+update
454 // can be merged into just a insert with this construct added:
455 // "ON DUPLICATE KEY UPDATE ".
456 // "pf_count=pf_count + VALUES(pf_count), ".
457 // "pf_time=pf_time + VALUES(pf_time)";
460 $dbw->ignoreErrors( $errorState );
464 * Get the function name of the current profiling section
466 function getCurrentSection() {
467 $elt = end( $this->mWorkStack
);
472 * Add an entry in the debug log file
474 * @param $s String to output
476 function debug( $s ) {
477 if( function_exists( 'wfDebug' ) ) {