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