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