Revert r55800 "bug 19646 Localization of img_auth.php - with enhancements"
[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 $functioname 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 $functioname 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 float $start
35 * @param float $elapsed 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 foreach( $this->mStack as $entry ){
263 $fname = $entry[0];
264 $start = $entry[2];
265 $end = $entry[4];
266 $elapsed = $end - $start;
267 $memory = $entry[5] - $entry[3];
268
269 if( $fname == '-overhead-total' ){
270 $overheadTotal[] = $elapsed;
271 $overheadMemory[] = $memory;
272 }
273 elseif( $fname == '-overhead-internal' ){
274 $overheadInternal[] = $elapsed;
275 }
276 }
277 $overheadTotal = array_sum( $overheadTotal ) / count( $overheadInternal );
278 $overheadMemory = array_sum( $overheadMemory ) / count( $overheadInternal );
279 $overheadInternal = array_sum( $overheadInternal ) / count( $overheadInternal );
280
281 # Collate
282 foreach( $this->mStack as $index => $entry ){
283 $fname = $entry[0];
284 $start = $entry[2];
285 $end = $entry[4];
286 $elapsed = $end - $start;
287
288 $memory = $entry[5] - $entry[3];
289 $subcalls = $this->calltreeCount( $this->mStack, $index );
290
291 if( !preg_match( '/^-overhead/', $fname ) ){
292 # Adjust for profiling overhead (except special values with elapsed=0
293 if( $elapsed ) {
294 $elapsed -= $overheadInternal;
295 $elapsed -= ($subcalls * $overheadTotal);
296 $memory -= ($subcalls * $overheadMemory);
297 }
298 }
299
300 if( !array_key_exists( $fname, $this->mCollated ) ){
301 $this->mCollated[$fname] = 0;
302 $this->mCalls[$fname] = 0;
303 $this->mMemory[$fname] = 0;
304 $this->mMin[$fname] = 1 << 24;
305 $this->mMax[$fname] = 0;
306 $this->mOverhead[$fname] = 0;
307 }
308
309 $this->mCollated[$fname] += $elapsed;
310 $this->mCalls[$fname]++;
311 $this->mMemory[$fname] += $memory;
312 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
313 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
314 $this->mOverhead[$fname] += $subcalls;
315 }
316
317 $total = @$this->mCollated['-total'];
318 $this->mCalls['-overhead-total'] = $profileCount;
319
320 # Output
321 arsort( $this->mCollated, SORT_NUMERIC );
322 foreach( $this->mCollated as $fname => $elapsed ){
323 $calls = $this->mCalls[$fname];
324 $percent = $total ? 100. * $elapsed / $total : 0;
325 $memory = $this->mMemory[$fname];
326 $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]);
327 # Log to the DB
328 if( $wgProfileToDatabase ) {
329 self::logToDB($fname, (float) ($elapsed * 1000), $calls, (float) ($memory) );
330 }
331 }
332 $prof .= "\nTotal: $total\n\n";
333
334 return $prof;
335 }
336
337 /**
338 * Counts the number of profiled function calls sitting under
339 * the given point in the call graph. Not the most efficient algo.
340 *
341 * @param $stack Array:
342 * @param $start Integer:
343 * @return Integer
344 * @private
345 */
346 function calltreeCount($stack, $start) {
347 $level = $stack[$start][1];
348 $count = 0;
349 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
350 $count ++;
351 }
352 return $count;
353 }
354
355 /**
356 * Log a function into the database.
357 *
358 * @param $name string: function name
359 * @param $timeSum float
360 * @param $eventCount int: number of times that function was called
361 */
362 static function logToDB( $name, $timeSum, $eventCount, $memorySum ){
363 # Do not log anything if database is readonly (bug 5375)
364 if( wfReadOnly() ) { return; }
365
366 global $wgProfilePerHost;
367
368 $dbw = wfGetDB( DB_MASTER );
369 if( !is_object( $dbw ) )
370 return false;
371 $errorState = $dbw->ignoreErrors( true );
372
373 $name = substr($name, 0, 255);
374
375 if( $wgProfilePerHost ){
376 $pfhost = wfHostname();
377 } else {
378 $pfhost = '';
379 }
380
381 // Kludge
382 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
383 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
384
385 $dbw->update( 'profiling',
386 array(
387 "pf_count=pf_count+{$eventCount}",
388 "pf_time=pf_time+{$timeSum}",
389 "pf_memory=pf_memory+{$memorySum}",
390 ),
391 array(
392 'pf_name' => $name,
393 'pf_server' => $pfhost,
394 ),
395 __METHOD__ );
396
397
398 $rc = $dbw->affectedRows();
399 if ($rc == 0) {
400 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
401 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
402 __METHOD__, array ('IGNORE'));
403 }
404 // When we upgrade to mysql 4.1, the insert+update
405 // can be merged into just a insert with this construct added:
406 // "ON DUPLICATE KEY UPDATE ".
407 // "pf_count=pf_count + VALUES(pf_count), ".
408 // "pf_time=pf_time + VALUES(pf_time)";
409 $dbw->ignoreErrors( $errorState );
410 }
411
412 /**
413 * Get the function name of the current profiling section
414 */
415 function getCurrentSection() {
416 $elt = end( $this->mWorkStack );
417 return $elt[0];
418 }
419
420 /**
421 * Get function caller
422 * @param $level int
423 */
424 static function getCaller( $level ) {
425 $backtrace = wfDebugBacktrace();
426 if ( isset( $backtrace[$level] ) ) {
427 if ( isset( $backtrace[$level]['class'] ) ) {
428 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
429 } else {
430 $caller = $backtrace[$level]['function'];
431 }
432 } else {
433 $caller = 'unknown';
434 }
435 return $caller;
436 }
437
438 /**
439 * Add an entry in the debug log file
440 * @param $s string to output
441 */
442 function debug( $s ) {
443 if( function_exists( 'wfDebug' ) ) {
444 wfDebug( $s );
445 }
446 }
447 }