Profiler can be constructed without param
[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 ( 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 ( isset( $wgProfiler['class'] ) ) {
28 Profiler::instance()->profileOut( $functionname );
29 }
30 }
31
32 /**
33 * @ingroup Profiler
34 * @todo document
35 */
36 class Profiler {
37 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
38 var $mCalls = array (), $mTotals = array ();
39 var $mTemplated = false;
40 var $mTimeMetric = 'wall';
41 private $mCollateDone = false;
42 protected $mProfileID = false;
43 private static $__instance = null;
44
45 function __construct( $params = null ) {
46 // Push an entry for the pre-profile setup time onto the stack
47 global $wgRequestTime;
48 if ( !empty( $wgRequestTime ) ) {
49 $this->mWorkStack[] = array( '-total', 0, $wgRequestTime, 0 );
50 $this->mStack[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
51 } else {
52 $this->profileIn( '-total' );
53 }
54 if ( isset( $params['timeMetric'] ) ) {
55 $this->mTimeMetric = $params['timeMetric'];
56 }
57 }
58
59 /**
60 * Singleton
61 * @return Profiler
62 */
63 public static function instance() {
64 if( is_null( self::$__instance ) ) {
65 global $wgProfiler;
66 if( is_array( $wgProfiler ) ) {
67 $class = isset( $wgProfiler['class'] ) ? $wgProfiler['class'] : 'ProfilerStub';
68 self::$__instance = new $class( $wgProfiler );
69 } elseif( $wgProfiler instanceof Profiler ) {
70 self::$__instance = $wgProfiler; // back-compat
71 } else {
72 self::$__instance = new ProfilerStub;
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 if ( $this->mTimeMetric === 'user' ) {
257 return $this->getUserTime();
258 } else {
259 return microtime(true);
260 }
261 }
262
263 function getUserTime() {
264 $ru = getrusage();
265 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6;
266 }
267
268 protected function collateData() {
269 if ( $this->mCollateDone ) {
270 return;
271 }
272 $this->mCollateDone = true;
273
274 $this->close();
275
276 $this->mCollated = array();
277 $this->mCalls = array();
278 $this->mMemory = array();
279
280 # Estimate profiling overhead
281 $profileCount = count($this->mStack);
282 self::calculateOverhead( $profileCount );
283
284 # First, subtract the overhead!
285 $overheadTotal = $overheadMemory = $overheadInternal = array();
286 foreach( $this->mStack as $entry ){
287 $fname = $entry[0];
288 $start = $entry[2];
289 $end = $entry[4];
290 $elapsed = $end - $start;
291 $memory = $entry[5] - $entry[3];
292
293 if( $fname == '-overhead-total' ){
294 $overheadTotal[] = $elapsed;
295 $overheadMemory[] = $memory;
296 }
297 elseif( $fname == '-overhead-internal' ){
298 $overheadInternal[] = $elapsed;
299 }
300 }
301 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
302 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
303 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
304
305 # Collate
306 foreach( $this->mStack as $index => $entry ){
307 $fname = $entry[0];
308 $start = $entry[2];
309 $end = $entry[4];
310 $elapsed = $end - $start;
311
312 $memory = $entry[5] - $entry[3];
313 $subcalls = $this->calltreeCount( $this->mStack, $index );
314
315 if( !preg_match( '/^-overhead/', $fname ) ){
316 # Adjust for profiling overhead (except special values with elapsed=0
317 if( $elapsed ) {
318 $elapsed -= $overheadInternal;
319 $elapsed -= ($subcalls * $overheadTotal);
320 $memory -= ($subcalls * $overheadMemory);
321 }
322 }
323
324 if( !array_key_exists( $fname, $this->mCollated ) ){
325 $this->mCollated[$fname] = 0;
326 $this->mCalls[$fname] = 0;
327 $this->mMemory[$fname] = 0;
328 $this->mMin[$fname] = 1 << 24;
329 $this->mMax[$fname] = 0;
330 $this->mOverhead[$fname] = 0;
331 }
332
333 $this->mCollated[$fname] += $elapsed;
334 $this->mCalls[$fname]++;
335 $this->mMemory[$fname] += $memory;
336 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
337 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
338 $this->mOverhead[$fname] += $subcalls;
339 }
340
341 $this->mCalls['-overhead-total'] = $profileCount;
342 arsort( $this->mCollated, SORT_NUMERIC );
343 }
344
345 /**
346 * Returns a list of profiled functions.
347 * Also log it into the database if $wgProfileToDatabase is set to true.
348 */
349 function getFunctionReport() {
350 $this->collateData();
351
352 $width = 140;
353 $nameWidth = $width - 65;
354 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
355 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
356 $prof = "\nProfiling data\n";
357 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
358
359 $total = @$this->mCollated['-total'];
360
361 foreach( $this->mCollated as $fname => $elapsed ){
362 $calls = $this->mCalls[$fname];
363 $percent = $total ? 100. * $elapsed / $total : 0;
364 $memory = $this->mMemory[$fname];
365 $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]);
366 }
367 $prof .= "\nTotal: $total\n\n";
368
369 return $prof;
370 }
371
372 /**
373 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
374 */
375 protected static function calculateOverhead( $profileCount ) {
376 wfProfileIn( '-overhead-total' );
377 for( $i = 0; $i < $profileCount; $i++ ){
378 wfProfileIn( '-overhead-internal' );
379 wfProfileOut( '-overhead-internal' );
380 }
381 wfProfileOut( '-overhead-total' );
382 }
383
384 /**
385 * Counts the number of profiled function calls sitting under
386 * the given point in the call graph. Not the most efficient algo.
387 *
388 * @param $stack Array:
389 * @param $start Integer:
390 * @return Integer
391 * @private
392 */
393 function calltreeCount($stack, $start) {
394 $level = $stack[$start][1];
395 $count = 0;
396 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
397 $count ++;
398 }
399 return $count;
400 }
401
402 /**
403 * Log the whole profiling data into the database.
404 */
405 public function logData(){
406 global $wgProfilePerHost, $wgProfileToDatabase;
407
408 # Do not log anything if database is readonly (bug 5375)
409 if( wfReadOnly() || !$wgProfileToDatabase ) {
410 return;
411 }
412
413 $dbw = wfGetDB( DB_MASTER );
414 if( !is_object( $dbw ) ) {
415 return;
416 }
417
418 $errorState = $dbw->ignoreErrors( true );
419
420 if( $wgProfilePerHost ){
421 $pfhost = wfHostname();
422 } else {
423 $pfhost = '';
424 }
425
426 $this->collateData();
427
428 foreach( $this->mCollated as $name => $elapsed ){
429 $eventCount = $this->mCalls[$name];
430 $timeSum = (float) ($elapsed * 1000);
431 $memorySum = (float)$this->mMemory[$name];
432 $name = substr($name, 0, 255);
433
434 // Kludge
435 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
436 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
437
438 $dbw->update( 'profiling',
439 array(
440 "pf_count=pf_count+{$eventCount}",
441 "pf_time=pf_time+{$timeSum}",
442 "pf_memory=pf_memory+{$memorySum}",
443 ),
444 array(
445 'pf_name' => $name,
446 'pf_server' => $pfhost,
447 ),
448 __METHOD__ );
449
450 $rc = $dbw->affectedRows();
451 if ( $rc == 0 ) {
452 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
453 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
454 __METHOD__, array ('IGNORE'));
455 }
456 // When we upgrade to mysql 4.1, the insert+update
457 // can be merged into just a insert with this construct added:
458 // "ON DUPLICATE KEY UPDATE ".
459 // "pf_count=pf_count + VALUES(pf_count), ".
460 // "pf_time=pf_time + VALUES(pf_time)";
461 }
462
463 $dbw->ignoreErrors( $errorState );
464 }
465
466 /**
467 * Get the function name of the current profiling section
468 */
469 function getCurrentSection() {
470 $elt = end( $this->mWorkStack );
471 return $elt[0];
472 }
473
474 /**
475 * Add an entry in the debug log file
476 *
477 * @param $s String to output
478 */
479 function debug( $s ) {
480 if( defined( 'MW_COMPILED' ) || function_exists( 'wfDebug' ) ) {
481 wfDebug( $s );
482 }
483 }
484 }