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