More profiler cleanup:
[lhc/web/wiklou.git] / includes / profiler / Profiler.php
1 <?php
2 /**
3 * @defgroup Profiler Profiler
4 *
5 * @file
6 * @ingroup Profiler
7 * This file is only included if profiling is enabled
8 */
9
10 /**
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]
14 */
15 $wgProfiler = array(
16 'class' => 'ProfilerStub',
17 );
18
19 /**
20 * Begin profiling of a function
21 * @param $functionname String: name of the function we will profile
22 */
23 function wfProfileIn( $functionname ) {
24 Profiler::instance()->profileIn( $functionname );
25 }
26
27 /**
28 * Stop profiling of a function
29 * @param $functionname String: name of the function we have profiled
30 */
31 function wfProfileOut( $functionname = 'missing' ) {
32 Profiler::instance()->profileOut( $functionname );
33 }
34
35 /**
36 * Returns a profiling output to be stored in debug file
37 */
38 function wfGetProfilingOutput() {
39 Profiler::instance()->getOutput();
40 }
41
42 /**
43 * Close opened profiling sections
44 */
45 function wfProfileClose() {
46 Profiler::instance()->close();
47 }
48
49 if (!function_exists('memory_get_usage')) {
50 # Old PHP or --enable-memory-limit not compiled in
51 function memory_get_usage() {
52 return 0;
53 }
54 }
55
56 /**
57 * @ingroup Profiler
58 * @todo document
59 */
60 class Profiler {
61 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
62 var $mCalls = array (), $mTotals = array ();
63 var $mTemplated = false;
64 private static $__instance = null;
65
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' );
74 }
75 }
76
77 /**
78 * Singleton
79 * @return Profiler
80 */
81 public static function instance() {
82 if( is_null( self::$__instance ) ) {
83 global $wgProfiler;
84 if( is_array( $wgProfiler ) ) {
85 $class = $wgProfiler['class'];
86 self::$__instance = new $class( $wgProfiler );
87 } elseif( $wgProfiler instanceof Profiler ) {
88 self::$__instance = $wgProfiler; // back-compat
89 } else {
90 throw new MWException( '$wgProfiler set to bogus value' );
91 }
92
93 }
94 return self::$__instance;
95 }
96
97 /**
98 * Called by wfProfieIn()
99 *
100 * @param $functionname String
101 */
102 public function profileIn( $functionname ) {
103 global $wgDebugFunctionEntry;
104 if( $wgDebugFunctionEntry ){
105 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
106 }
107
108 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
109 }
110
111 /**
112 * Called by wfProfieOut()
113 *
114 * @param $functionname String
115 */
116 public function profileOut($functionname) {
117 global $wgDebugFunctionEntry;
118 $memory = memory_get_usage();
119 $time = $this->getTime();
120
121 if( $wgDebugFunctionEntry ){
122 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
123 }
124
125 $bit = array_pop($this->mWorkStack);
126
127 if (!$bit) {
128 $this->debug("Profiling error, !\$bit: $functionname\n");
129 } else {
130 //if( $wgDebugProfiling ){
131 if( $functionname == 'close' ){
132 $message = "Profile section ended by close(): {$bit[0]}";
133 $this->debug( "$message\n" );
134 $this->mStack[] = array( $message, 0, '0 0', 0, '0 0', 0 );
135 }
136 elseif( $bit[0] != $functionname ){
137 $message = "Profiling error: in({$bit[0]}), out($functionname)";
138 $this->debug( "$message\n" );
139 $this->mStack[] = array( $message, 0, '0 0', 0, '0 0', 0 );
140 }
141 //}
142 $bit[] = $time;
143 $bit[] = $memory;
144 $this->mStack[] = $bit;
145 }
146 }
147
148 /**
149 * called by wfProfileClose()
150 */
151 public function close() {
152 while( count( $this->mWorkStack ) ){
153 $this->profileOut( 'close' );
154 }
155 }
156
157 /**
158 * Mark this call as templated or not
159 *
160 * @param $t Boolean
161 */
162 function setTemplated( $t ) {
163 $this->mTemplated = $t;
164 }
165
166 /**
167 * Called by wfGetProfilingOutput()
168 */
169 public function getOutput() {
170 global $wgDebugFunctionEntry, $wgProfileCallTree;
171 $wgDebugFunctionEntry = false;
172
173 if( !count( $this->mStack ) && !count( $this->mCollated ) ){
174 return "No profiling output\n";
175 }
176 $this->close();
177
178 if( $wgProfileCallTree ) {
179 global $wgProfileToDatabase;
180 # XXX: We must call $this->getFunctionReport() to log to the DB
181 if( $wgProfileToDatabase ) {
182 $this->getFunctionReport();
183 }
184 return $this->getCallTree();
185 } else {
186 return $this->getFunctionReport();
187 }
188 }
189
190 /**
191 * Returns a tree of function call instead of a list of functions
192 */
193 function getCallTree() {
194 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
195 }
196
197 /**
198 * Recursive function the format the current profiling array into a tree
199 *
200 * @param $stack profiling array
201 */
202 function remapCallTree( $stack ) {
203 if( count( $stack ) < 2 ){
204 return $stack;
205 }
206 $outputs = array ();
207 for( $max = count( $stack ) - 1; $max > 0; ){
208 /* Find all items under this entry */
209 $level = $stack[$max][1];
210 $working = array ();
211 for( $i = $max -1; $i >= 0; $i-- ){
212 if( $stack[$i][1] > $level ){
213 $working[] = $stack[$i];
214 } else {
215 break;
216 }
217 }
218 $working = $this->remapCallTree( array_reverse( $working ) );
219 $output = array();
220 foreach( $working as $item ){
221 array_push( $output, $item );
222 }
223 array_unshift( $output, $stack[$max] );
224 $max = $i;
225
226 array_unshift( $outputs, $output );
227 }
228 $final = array();
229 foreach( $outputs as $output ){
230 foreach( $output as $item ){
231 $final[] = $item;
232 }
233 }
234 return $final;
235 }
236
237 /**
238 * Callback to get a formatted line for the call tree
239 */
240 function getCallTreeLine( $entry ) {
241 list( $fname, $level, $start, /* $x */, $end) = $entry;
242 $delta = $end - $start;
243 $space = str_repeat(' ', $level);
244 # The ugly double sprintf is to work around a PHP bug,
245 # which has been fixed in recent releases.
246 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
247 }
248
249 function getTime() {
250 return microtime(true);
251 #return $this->getUserTime();
252 }
253
254 function getUserTime() {
255 $ru = getrusage();
256 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6;
257 }
258
259 /**
260 * Returns a list of profiled functions.
261 * Also log it into the database if $wgProfileToDatabase is set to true.
262 */
263 function getFunctionReport() {
264 global $wgProfileToDatabase;
265
266 $width = 140;
267 $nameWidth = $width - 65;
268 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
269 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
270 $prof = "\nProfiling data\n";
271 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
272 $this->mCollated = array ();
273 $this->mCalls = array ();
274 $this->mMemory = array ();
275
276 # Estimate profiling overhead
277 $profileCount = count($this->mStack);
278 self::calculateOverhead( $profileCount );
279
280 # First, subtract the overhead!
281 $overheadTotal = $overheadMemory = $overheadInternal = array();
282 foreach( $this->mStack as $entry ){
283 $fname = $entry[0];
284 $start = $entry[2];
285 $end = $entry[4];
286 $elapsed = $end - $start;
287 $memory = $entry[5] - $entry[3];
288
289 if( $fname == '-overhead-total' ){
290 $overheadTotal[] = $elapsed;
291 $overheadMemory[] = $memory;
292 }
293 elseif( $fname == '-overhead-internal' ){
294 $overheadInternal[] = $elapsed;
295 }
296 }
297 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
298 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
299 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
300
301 # Collate
302 foreach( $this->mStack as $index => $entry ){
303 $fname = $entry[0];
304 $start = $entry[2];
305 $end = $entry[4];
306 $elapsed = $end - $start;
307
308 $memory = $entry[5] - $entry[3];
309 $subcalls = $this->calltreeCount( $this->mStack, $index );
310
311 if( !preg_match( '/^-overhead/', $fname ) ){
312 # Adjust for profiling overhead (except special values with elapsed=0
313 if( $elapsed ) {
314 $elapsed -= $overheadInternal;
315 $elapsed -= ($subcalls * $overheadTotal);
316 $memory -= ($subcalls * $overheadMemory);
317 }
318 }
319
320 if( !array_key_exists( $fname, $this->mCollated ) ){
321 $this->mCollated[$fname] = 0;
322 $this->mCalls[$fname] = 0;
323 $this->mMemory[$fname] = 0;
324 $this->mMin[$fname] = 1 << 24;
325 $this->mMax[$fname] = 0;
326 $this->mOverhead[$fname] = 0;
327 }
328
329 $this->mCollated[$fname] += $elapsed;
330 $this->mCalls[$fname]++;
331 $this->mMemory[$fname] += $memory;
332 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
333 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
334 $this->mOverhead[$fname] += $subcalls;
335 }
336
337 $total = @$this->mCollated['-total'];
338 $this->mCalls['-overhead-total'] = $profileCount;
339
340 # Output
341 arsort( $this->mCollated, SORT_NUMERIC );
342 foreach( $this->mCollated as $fname => $elapsed ){
343 $calls = $this->mCalls[$fname];
344 $percent = $total ? 100. * $elapsed / $total : 0;
345 $memory = $this->mMemory[$fname];
346 $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]);
347 # Log to the DB
348 if( $wgProfileToDatabase ) {
349 self::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
350 }
351 }
352 $prof .= "\nTotal: $total\n\n";
353
354 return $prof;
355 }
356
357 /**
358 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
359 */
360 protected static function calculateOverhead( $profileCount ) {
361 wfProfileIn( '-overhead-total' );
362 for( $i = 0; $i < $profileCount; $i++ ){
363 wfProfileIn( '-overhead-internal' );
364 wfProfileOut( '-overhead-internal' );
365 }
366 wfProfileOut( '-overhead-total' );
367 }
368
369 /**
370 * Counts the number of profiled function calls sitting under
371 * the given point in the call graph. Not the most efficient algo.
372 *
373 * @param $stack Array:
374 * @param $start Integer:
375 * @return Integer
376 * @private
377 */
378 function calltreeCount($stack, $start) {
379 $level = $stack[$start][1];
380 $count = 0;
381 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
382 $count ++;
383 }
384 return $count;
385 }
386
387 /**
388 * Log a function into the database.
389 *
390 * @param $name String: function name
391 * @param $timeSum Float
392 * @param $eventCount Integer: number of times that function was called
393 * @param $memorySum Integer: memory used by the function
394 */
395 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
396 # Do not log anything if database is readonly (bug 5375)
397 if( wfReadOnly() ) { return; }
398
399 global $wgProfilePerHost;
400
401 $dbw = wfGetDB( DB_MASTER );
402 if( !is_object( $dbw ) )
403 return false;
404 $errorState = $dbw->ignoreErrors( true );
405
406 $name = substr($name, 0, 255);
407
408 if( $wgProfilePerHost ){
409 $pfhost = wfHostname();
410 } else {
411 $pfhost = '';
412 }
413
414 // Kludge
415 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
416 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
417
418 $dbw->update( 'profiling',
419 array(
420 "pf_count=pf_count+{$eventCount}",
421 "pf_time=pf_time+{$timeSum}",
422 "pf_memory=pf_memory+{$memorySum}",
423 ),
424 array(
425 'pf_name' => $name,
426 'pf_server' => $pfhost,
427 ),
428 __METHOD__ );
429
430
431 $rc = $dbw->affectedRows();
432 if ($rc == 0) {
433 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
434 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
435 __METHOD__, array ('IGNORE'));
436 }
437 // When we upgrade to mysql 4.1, the insert+update
438 // can be merged into just a insert with this construct added:
439 // "ON DUPLICATE KEY UPDATE ".
440 // "pf_count=pf_count + VALUES(pf_count), ".
441 // "pf_time=pf_time + VALUES(pf_time)";
442 $dbw->ignoreErrors( $errorState );
443 }
444
445 /**
446 * Get the function name of the current profiling section
447 */
448 function getCurrentSection() {
449 $elt = end( $this->mWorkStack );
450 return $elt[0];
451 }
452
453 /**
454 * Get function caller
455 *
456 * @param $level Integer
457 */
458 static function getCaller( $level ) {
459 $backtrace = wfDebugBacktrace();
460 if ( isset( $backtrace[$level] ) ) {
461 if ( isset( $backtrace[$level]['class'] ) ) {
462 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
463 } else {
464 $caller = $backtrace[$level]['function'];
465 }
466 } else {
467 $caller = 'unknown';
468 }
469 return $caller;
470 }
471
472 /**
473 * Add an entry in the debug log file
474 *
475 * @param $s String to output
476 */
477 function debug( $s ) {
478 if( function_exists( 'wfDebug' ) ) {
479 wfDebug( $s );
480 }
481 }
482 }