Implemented param tracking for hook users, feels a bit hackish
[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 * @ingroup Profiler
37 * @todo document
38 */
39 class Profiler {
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;
46
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 );
53 } else {
54 $this->profileIn( '-total' );
55 }
56 }
57
58 /**
59 * Singleton
60 * @return Profiler
61 */
62 public static function instance() {
63 if( is_null( self::$__instance ) ) {
64 global $wgProfiler;
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
70 } else {
71 throw new MWException( '$wgProfiler set to bogus value' );
72 }
73
74 }
75 return self::$__instance;
76 }
77
78 /**
79 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
80 * @param $p Profiler object
81 */
82 public static function setInstance( Profiler $p ) {
83 self::$__instance = $p;
84 }
85
86 /**
87 * Return whether this a stub profiler
88 *
89 * @return Boolean
90 */
91 public function isStub() {
92 return false;
93 }
94
95 public function setProfileID( $id ) {
96 $this->mProfileID = $id;
97 }
98
99 public function getProfileID() {
100 if ( $this->mProfileID === false ) {
101 return wfWikiID();
102 } else {
103 return $this->mProfileID;
104 }
105 }
106
107 /**
108 * Called by wfProfieIn()
109 *
110 * @param $functionname String
111 */
112 public function profileIn( $functionname ) {
113 global $wgDebugFunctionEntry;
114 if( $wgDebugFunctionEntry ){
115 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
116 }
117
118 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
119 }
120
121 /**
122 * Called by wfProfieOut()
123 *
124 * @param $functionname String
125 */
126 public function profileOut( $functionname ) {
127 global $wgDebugFunctionEntry;
128 $memory = memory_get_usage();
129 $time = $this->getTime();
130
131 if( $wgDebugFunctionEntry ){
132 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
133 }
134
135 $bit = array_pop($this->mWorkStack);
136
137 if (!$bit) {
138 $this->debug("Profiling error, !\$bit: $functionname\n");
139 } else {
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 );
145 }
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 );
150 }
151 //}
152 $bit[] = $time;
153 $bit[] = $memory;
154 $this->mStack[] = $bit;
155 }
156 }
157
158 /**
159 * Close opened profiling sections
160 */
161 public function close() {
162 while( count( $this->mWorkStack ) ){
163 $this->profileOut( 'close' );
164 }
165 }
166
167 /**
168 * Mark this call as templated or not
169 *
170 * @param $t Boolean
171 */
172 function setTemplated( $t ) {
173 $this->mTemplated = $t;
174 }
175
176 /**
177 * Returns a profiling output to be stored in debug file
178 *
179 * @return String
180 */
181 public function getOutput() {
182 global $wgDebugFunctionEntry, $wgProfileCallTree;
183 $wgDebugFunctionEntry = false;
184
185 if( !count( $this->mStack ) && !count( $this->mCollated ) ){
186 return "No profiling output\n";
187 }
188
189 if( $wgProfileCallTree ) {
190 return $this->getCallTree();
191 } else {
192 return $this->getFunctionReport();
193 }
194 }
195
196 /**
197 * Returns a tree of function call instead of a list of functions
198 */
199 function getCallTree() {
200 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
201 }
202
203 /**
204 * Recursive function the format the current profiling array into a tree
205 *
206 * @param $stack profiling array
207 */
208 function remapCallTree( $stack ) {
209 if( count( $stack ) < 2 ){
210 return $stack;
211 }
212 $outputs = array ();
213 for( $max = count( $stack ) - 1; $max > 0; ){
214 /* Find all items under this entry */
215 $level = $stack[$max][1];
216 $working = array ();
217 for( $i = $max -1; $i >= 0; $i-- ){
218 if( $stack[$i][1] > $level ){
219 $working[] = $stack[$i];
220 } else {
221 break;
222 }
223 }
224 $working = $this->remapCallTree( array_reverse( $working ) );
225 $output = array();
226 foreach( $working as $item ){
227 array_push( $output, $item );
228 }
229 array_unshift( $output, $stack[$max] );
230 $max = $i;
231
232 array_unshift( $outputs, $output );
233 }
234 $final = array();
235 foreach( $outputs as $output ){
236 foreach( $output as $item ){
237 $final[] = $item;
238 }
239 }
240 return $final;
241 }
242
243 /**
244 * Callback to get a formatted line for the call tree
245 */
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 );
253 }
254
255 function getTime() {
256 return microtime(true);
257 #return $this->getUserTime();
258 }
259
260 function getUserTime() {
261 $ru = getrusage();
262 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6;
263 }
264
265 protected function collateData() {
266 if ( $this->mCollateDone ) {
267 return;
268 }
269 $this->mCollateDone = true;
270
271 $this->close();
272
273 $this->mCollated = array();
274 $this->mCalls = array();
275 $this->mMemory = array();
276
277 # Estimate profiling overhead
278 $profileCount = count($this->mStack);
279 self::calculateOverhead( $profileCount );
280
281 # First, subtract the overhead!
282 $overheadTotal = $overheadMemory = $overheadInternal = array();
283 foreach( $this->mStack as $entry ){
284 $fname = $entry[0];
285 $start = $entry[2];
286 $end = $entry[4];
287 $elapsed = $end - $start;
288 $memory = $entry[5] - $entry[3];
289
290 if( $fname == '-overhead-total' ){
291 $overheadTotal[] = $elapsed;
292 $overheadMemory[] = $memory;
293 }
294 elseif( $fname == '-overhead-internal' ){
295 $overheadInternal[] = $elapsed;
296 }
297 }
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;
301
302 # Collate
303 foreach( $this->mStack as $index => $entry ){
304 $fname = $entry[0];
305 $start = $entry[2];
306 $end = $entry[4];
307 $elapsed = $end - $start;
308
309 $memory = $entry[5] - $entry[3];
310 $subcalls = $this->calltreeCount( $this->mStack, $index );
311
312 if( !preg_match( '/^-overhead/', $fname ) ){
313 # Adjust for profiling overhead (except special values with elapsed=0
314 if( $elapsed ) {
315 $elapsed -= $overheadInternal;
316 $elapsed -= ($subcalls * $overheadTotal);
317 $memory -= ($subcalls * $overheadMemory);
318 }
319 }
320
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;
328 }
329
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;
336 }
337
338 $this->mCalls['-overhead-total'] = $profileCount;
339 arsort( $this->mCollated, SORT_NUMERIC );
340 }
341
342 /**
343 * Returns a list of profiled functions.
344 * Also log it into the database if $wgProfileToDatabase is set to true.
345 */
346 function getFunctionReport() {
347 $this->collateData();
348
349 $width = 140;
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' );
355
356 $total = @$this->mCollated['-total'];
357
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]);
363 }
364 $prof .= "\nTotal: $total\n\n";
365
366 return $prof;
367 }
368
369 /**
370 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
371 */
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' );
377 }
378 wfProfileOut( '-overhead-total' );
379 }
380
381 /**
382 * Counts the number of profiled function calls sitting under
383 * the given point in the call graph. Not the most efficient algo.
384 *
385 * @param $stack Array:
386 * @param $start Integer:
387 * @return Integer
388 * @private
389 */
390 function calltreeCount($stack, $start) {
391 $level = $stack[$start][1];
392 $count = 0;
393 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
394 $count ++;
395 }
396 return $count;
397 }
398
399 /**
400 * Log the whole profiling data into the database.
401 */
402 public function logData(){
403 global $wgProfilePerHost, $wgProfileToDatabase;
404
405 # Do not log anything if database is readonly (bug 5375)
406 if( wfReadOnly() || !$wgProfileToDatabase ) {
407 return;
408 }
409
410 $dbw = wfGetDB( DB_MASTER );
411 if( !is_object( $dbw ) ) {
412 return;
413 }
414
415 $errorState = $dbw->ignoreErrors( true );
416
417 if( $wgProfilePerHost ){
418 $pfhost = wfHostname();
419 } else {
420 $pfhost = '';
421 }
422
423 $this->collateData();
424
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);
430
431 // Kludge
432 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
433 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
434
435 $dbw->update( 'profiling',
436 array(
437 "pf_count=pf_count+{$eventCount}",
438 "pf_time=pf_time+{$timeSum}",
439 "pf_memory=pf_memory+{$memorySum}",
440 ),
441 array(
442 'pf_name' => $name,
443 'pf_server' => $pfhost,
444 ),
445 __METHOD__ );
446
447 $rc = $dbw->affectedRows();
448 if ( $rc == 0 ) {
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'));
452 }
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)";
458 }
459
460 $dbw->ignoreErrors( $errorState );
461 }
462
463 /**
464 * Get the function name of the current profiling section
465 */
466 function getCurrentSection() {
467 $elt = end( $this->mWorkStack );
468 return $elt[0];
469 }
470
471 /**
472 * Add an entry in the debug log file
473 *
474 * @param $s String to output
475 */
476 function debug( $s ) {
477 if( function_exists( 'wfDebug' ) ) {
478 wfDebug( $s );
479 }
480 }
481 }