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