More return documentation
[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 * @return string
209 */
210 function getCallTree() {
211 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
212 }
213
214 /**
215 * Recursive function the format the current profiling array into a tree
216 *
217 * @param $stack array profiling array
218 * @return array
219 */
220 function remapCallTree( $stack ) {
221 if( count( $stack ) < 2 ){
222 return $stack;
223 }
224 $outputs = array ();
225 for( $max = count( $stack ) - 1; $max > 0; ){
226 /* Find all items under this entry */
227 $level = $stack[$max][1];
228 $working = array ();
229 for( $i = $max -1; $i >= 0; $i-- ){
230 if( $stack[$i][1] > $level ){
231 $working[] = $stack[$i];
232 } else {
233 break;
234 }
235 }
236 $working = $this->remapCallTree( array_reverse( $working ) );
237 $output = array();
238 foreach( $working as $item ){
239 array_push( $output, $item );
240 }
241 array_unshift( $output, $stack[$max] );
242 $max = $i;
243
244 array_unshift( $outputs, $output );
245 }
246 $final = array();
247 foreach( $outputs as $output ){
248 foreach( $output as $item ){
249 $final[] = $item;
250 }
251 }
252 return $final;
253 }
254
255 /**
256 * Callback to get a formatted line for the call tree
257 * @return string
258 */
259 function getCallTreeLine( $entry ) {
260 list( $fname, $level, $start, /* $x */, $end) = $entry;
261 $delta = $end - $start;
262 $space = str_repeat(' ', $level);
263 # The ugly double sprintf is to work around a PHP bug,
264 # which has been fixed in recent releases.
265 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
266 }
267
268 function getTime() {
269 if ( $this->mTimeMetric === 'user' ) {
270 return $this->getUserTime();
271 } else {
272 return microtime( true );
273 }
274 }
275
276 function getUserTime() {
277 $ru = getrusage();
278 return $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
279 }
280
281 private function getInitialTime() {
282 global $wgRequestTime, $wgRUstart;
283
284 if ( $this->mTimeMetric === 'user' ) {
285 if ( count( $wgRUstart ) ) {
286 return $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
287 } else {
288 return null;
289 }
290 } else {
291 if ( empty( $wgRequestTime ) ) {
292 return null;
293 } else {
294 return $wgRequestTime;
295 }
296 }
297 }
298
299 protected function collateData() {
300 if ( $this->mCollateDone ) {
301 return;
302 }
303 $this->mCollateDone = true;
304
305 $this->close();
306
307 $this->mCollated = array();
308 $this->mCalls = array();
309 $this->mMemory = array();
310
311 # Estimate profiling overhead
312 $profileCount = count($this->mStack);
313 self::calculateOverhead( $profileCount );
314
315 # First, subtract the overhead!
316 $overheadTotal = $overheadMemory = $overheadInternal = array();
317 foreach( $this->mStack as $entry ){
318 $fname = $entry[0];
319 $start = $entry[2];
320 $end = $entry[4];
321 $elapsed = $end - $start;
322 $memory = $entry[5] - $entry[3];
323
324 if( $fname == '-overhead-total' ){
325 $overheadTotal[] = $elapsed;
326 $overheadMemory[] = $memory;
327 }
328 elseif( $fname == '-overhead-internal' ){
329 $overheadInternal[] = $elapsed;
330 }
331 }
332 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
333 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
334 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
335
336 # Collate
337 foreach( $this->mStack as $index => $entry ){
338 $fname = $entry[0];
339 $start = $entry[2];
340 $end = $entry[4];
341 $elapsed = $end - $start;
342
343 $memory = $entry[5] - $entry[3];
344 $subcalls = $this->calltreeCount( $this->mStack, $index );
345
346 if( !preg_match( '/^-overhead/', $fname ) ){
347 # Adjust for profiling overhead (except special values with elapsed=0
348 if( $elapsed ) {
349 $elapsed -= $overheadInternal;
350 $elapsed -= ($subcalls * $overheadTotal);
351 $memory -= ($subcalls * $overheadMemory);
352 }
353 }
354
355 if( !array_key_exists( $fname, $this->mCollated ) ){
356 $this->mCollated[$fname] = 0;
357 $this->mCalls[$fname] = 0;
358 $this->mMemory[$fname] = 0;
359 $this->mMin[$fname] = 1 << 24;
360 $this->mMax[$fname] = 0;
361 $this->mOverhead[$fname] = 0;
362 }
363
364 $this->mCollated[$fname] += $elapsed;
365 $this->mCalls[$fname]++;
366 $this->mMemory[$fname] += $memory;
367 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
368 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
369 $this->mOverhead[$fname] += $subcalls;
370 }
371
372 $this->mCalls['-overhead-total'] = $profileCount;
373 arsort( $this->mCollated, SORT_NUMERIC );
374 }
375
376 /**
377 * Returns a list of profiled functions.
378 *
379 * @return string
380 */
381 function getFunctionReport() {
382 $this->collateData();
383
384 $width = 140;
385 $nameWidth = $width - 65;
386 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
387 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
388 $prof = "\nProfiling data\n";
389 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
390
391 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
392
393 foreach( $this->mCollated as $fname => $elapsed ){
394 $calls = $this->mCalls[$fname];
395 $percent = $total ? 100. * $elapsed / $total : 0;
396 $memory = $this->mMemory[$fname];
397 $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]);
398 }
399 $prof .= "\nTotal: $total\n\n";
400
401 return $prof;
402 }
403
404 /**
405 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
406 */
407 protected static function calculateOverhead( $profileCount ) {
408 wfProfileIn( '-overhead-total' );
409 for( $i = 0; $i < $profileCount; $i++ ){
410 wfProfileIn( '-overhead-internal' );
411 wfProfileOut( '-overhead-internal' );
412 }
413 wfProfileOut( '-overhead-total' );
414 }
415
416 /**
417 * Counts the number of profiled function calls sitting under
418 * the given point in the call graph. Not the most efficient algo.
419 *
420 * @param $stack Array:
421 * @param $start Integer:
422 * @return Integer
423 * @private
424 */
425 function calltreeCount($stack, $start) {
426 $level = $stack[$start][1];
427 $count = 0;
428 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
429 $count ++;
430 }
431 return $count;
432 }
433
434 /**
435 * Log the whole profiling data into the database.
436 */
437 public function logData(){
438 global $wgProfilePerHost, $wgProfileToDatabase;
439
440 # Do not log anything if database is readonly (bug 5375)
441 if( wfReadOnly() || !$wgProfileToDatabase ) {
442 return;
443 }
444
445 $dbw = wfGetDB( DB_MASTER );
446 if( !is_object( $dbw ) ) {
447 return;
448 }
449
450 $errorState = $dbw->ignoreErrors( true );
451
452 if( $wgProfilePerHost ){
453 $pfhost = wfHostname();
454 } else {
455 $pfhost = '';
456 }
457
458 $this->collateData();
459
460 foreach( $this->mCollated as $name => $elapsed ){
461 $eventCount = $this->mCalls[$name];
462 $timeSum = (float) ($elapsed * 1000);
463 $memorySum = (float)$this->mMemory[$name];
464 $name = substr($name, 0, 255);
465
466 // Kludge
467 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
468 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
469
470 $dbw->update( 'profiling',
471 array(
472 "pf_count=pf_count+{$eventCount}",
473 "pf_time=pf_time+{$timeSum}",
474 "pf_memory=pf_memory+{$memorySum}",
475 ),
476 array(
477 'pf_name' => $name,
478 'pf_server' => $pfhost,
479 ),
480 __METHOD__ );
481
482 $rc = $dbw->affectedRows();
483 if ( $rc == 0 ) {
484 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
485 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
486 __METHOD__, array ('IGNORE'));
487 }
488 // When we upgrade to mysql 4.1, the insert+update
489 // can be merged into just a insert with this construct added:
490 // "ON DUPLICATE KEY UPDATE ".
491 // "pf_count=pf_count + VALUES(pf_count), ".
492 // "pf_time=pf_time + VALUES(pf_time)";
493 }
494
495 $dbw->ignoreErrors( $errorState );
496 }
497
498 /**
499 * Get the function name of the current profiling section
500 * @return
501 */
502 function getCurrentSection() {
503 $elt = end( $this->mWorkStack );
504 return $elt[0];
505 }
506
507 /**
508 * Add an entry in the debug log file
509 *
510 * @param $s String to output
511 */
512 function debug( $s ) {
513 if( defined( 'MW_COMPILED' ) || function_exists( 'wfDebug' ) ) {
514 wfDebug( $s );
515 }
516 }
517 }