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