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