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