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