Merge "Remove subpage from form target on Special:BlockList"
[lhc/web/wiklou.git] / includes / profiler / Profiler.php
1 <?php
2 /**
3 * Base class and functions for profiling.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Profiler
22 * This file is only included if profiling is enabled
23 */
24
25 /**
26 * @defgroup Profiler Profiler
27 */
28
29 /**
30 * Begin profiling of a function
31 * @param string $functionname name of the function we will profile
32 */
33 function wfProfileIn( $functionname ) {
34 global $wgProfiler;
35 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
36 Profiler::instance()->profileIn( $functionname );
37 }
38 }
39
40 /**
41 * Stop profiling of a function
42 * @param string $functionname name of the function we have profiled
43 */
44 function wfProfileOut( $functionname = 'missing' ) {
45 global $wgProfiler;
46 if ( $wgProfiler instanceof Profiler || isset( $wgProfiler['class'] ) ) {
47 Profiler::instance()->profileOut( $functionname );
48 }
49 }
50
51 /**
52 * @ingroup Profiler
53 * @todo document
54 */
55 class Profiler {
56 protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
57 $mCalls = array(), $mTotals = array();
58 protected $mTimeMetric = 'wall';
59 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
60 private static $__instance = null;
61
62 function __construct( $params ) {
63 if ( isset( $params['timeMetric'] ) ) {
64 $this->mTimeMetric = $params['timeMetric'];
65 }
66 if ( isset( $params['profileID'] ) ) {
67 $this->mProfileID = $params['profileID'];
68 }
69
70 $this->addInitialStack();
71 }
72
73 /**
74 * Singleton
75 * @return Profiler
76 */
77 public static function instance() {
78 if ( is_null( self::$__instance ) ) {
79 global $wgProfiler;
80 if ( is_array( $wgProfiler ) ) {
81 if ( !isset( $wgProfiler['class'] ) ) {
82 wfDebug( __METHOD__ . " called without \$wgProfiler['class']"
83 . " set, falling back to ProfilerStub for safety\n" );
84 $class = 'ProfilerStub';
85 } else {
86 $class = $wgProfiler['class'];
87 }
88 self::$__instance = new $class( $wgProfiler );
89 } elseif ( $wgProfiler instanceof Profiler ) {
90 self::$__instance = $wgProfiler; // back-compat
91 } else {
92 wfDebug( __METHOD__ . ' called with bogus $wgProfiler setting,'
93 . " falling back to ProfilerStub for safety\n" );
94 self::$__instance = new ProfilerStub( $wgProfiler );
95 }
96 }
97 return self::$__instance;
98 }
99
100 /**
101 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
102 * @param $p Profiler object
103 */
104 public static function setInstance( Profiler $p ) {
105 self::$__instance = $p;
106 }
107
108 /**
109 * Return whether this a stub profiler
110 *
111 * @return Boolean
112 */
113 public function isStub() {
114 return false;
115 }
116
117 /**
118 * Return whether this profiler stores data
119 *
120 * @see Profiler::logData()
121 * @return Boolean
122 */
123 public function isPersistent() {
124 return true;
125 }
126
127 public function setProfileID( $id ) {
128 $this->mProfileID = $id;
129 }
130
131 public function getProfileID() {
132 if ( $this->mProfileID === false ) {
133 return wfWikiID();
134 } else {
135 return $this->mProfileID;
136 }
137 }
138
139 /**
140 * Add the inital item in the stack.
141 */
142 protected function addInitialStack() {
143 // Push an entry for the pre-profile setup time onto the stack
144 $initial = $this->getInitialTime();
145 if ( $initial !== null ) {
146 $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
147 $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
148 } else {
149 $this->profileIn( '-total' );
150 }
151 }
152
153 /**
154 * Called by wfProfieIn()
155 *
156 * @param $functionname String
157 */
158 public function profileIn( $functionname ) {
159 global $wgDebugFunctionEntry;
160 if ( $wgDebugFunctionEntry ) {
161 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
162 }
163
164 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
165 }
166
167 /**
168 * Called by wfProfieOut()
169 *
170 * @param $functionname String
171 */
172 public function profileOut( $functionname ) {
173 global $wgDebugFunctionEntry;
174 $memory = memory_get_usage();
175 $time = $this->getTime();
176
177 if ( $wgDebugFunctionEntry ) {
178 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
179 }
180
181 $bit = array_pop( $this->mWorkStack );
182
183 if ( !$bit ) {
184 $this->debug( "Profiling error, !\$bit: $functionname\n" );
185 } else {
186 //if( $wgDebugProfiling ) {
187 if ( $functionname == 'close' ) {
188 $message = "Profile section ended by close(): {$bit[0]}";
189 $this->debug( "$message\n" );
190 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
191 } elseif ( $bit[0] != $functionname ) {
192 $message = "Profiling error: in({$bit[0]}), out($functionname)";
193 $this->debug( "$message\n" );
194 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
195 }
196 //}
197 $bit[] = $time;
198 $bit[] = $memory;
199 $this->mStack[] = $bit;
200 }
201 }
202
203 /**
204 * Close opened profiling sections
205 */
206 public function close() {
207 while ( count( $this->mWorkStack ) ) {
208 $this->profileOut( 'close' );
209 }
210 }
211
212 /**
213 * Mark this call as templated or not
214 *
215 * @param $t Boolean
216 */
217 function setTemplated( $t ) {
218 $this->mTemplated = $t;
219 }
220
221 /**
222 * Returns a profiling output to be stored in debug file
223 *
224 * @return String
225 */
226 public function getOutput() {
227 global $wgDebugFunctionEntry, $wgProfileCallTree;
228 $wgDebugFunctionEntry = false;
229
230 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
231 return "No profiling output\n";
232 }
233
234 if ( $wgProfileCallTree ) {
235 return $this->getCallTree();
236 } else {
237 return $this->getFunctionReport();
238 }
239 }
240
241 /**
242 * Returns a tree of function call instead of a list of functions
243 * @return string
244 */
245 function getCallTree() {
246 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
247 }
248
249 /**
250 * Recursive function the format the current profiling array into a tree
251 *
252 * @param array $stack profiling array
253 * @return array
254 */
255 function remapCallTree( $stack ) {
256 if ( count( $stack ) < 2 ) {
257 return $stack;
258 }
259 $outputs = array();
260 for ( $max = count( $stack ) - 1; $max > 0; ) {
261 /* Find all items under this entry */
262 $level = $stack[$max][1];
263 $working = array();
264 for ( $i = $max -1; $i >= 0; $i-- ) {
265 if ( $stack[$i][1] > $level ) {
266 $working[] = $stack[$i];
267 } else {
268 break;
269 }
270 }
271 $working = $this->remapCallTree( array_reverse( $working ) );
272 $output = array();
273 foreach ( $working as $item ) {
274 array_push( $output, $item );
275 }
276 array_unshift( $output, $stack[$max] );
277 $max = $i;
278
279 array_unshift( $outputs, $output );
280 }
281 $final = array();
282 foreach ( $outputs as $output ) {
283 foreach ( $output as $item ) {
284 $final[] = $item;
285 }
286 }
287 return $final;
288 }
289
290 /**
291 * Callback to get a formatted line for the call tree
292 * @return string
293 */
294 function getCallTreeLine( $entry ) {
295 list( $fname, $level, $start, /* $x */, $end ) = $entry;
296 $delta = $end - $start;
297 $space = str_repeat( ' ', $level );
298 # The ugly double sprintf is to work around a PHP bug,
299 # which has been fixed in recent releases.
300 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
301 }
302
303 /**
304 * Get the initial time of the request, based either on $wgRequestTime or
305 * $wgRUstart. Will return null if not able to find data.
306 *
307 * @param string|false $metric metric to use, with the following possibilities:
308 * - user: User CPU time (without system calls)
309 * - cpu: Total CPU time (user and system calls)
310 * - wall (or any other string): elapsed time
311 * - false (default): will fall back to default metric
312 * @return float|null
313 */
314 function getTime( $metric = false ) {
315 if ( $metric === false ) {
316 $metric = $this->mTimeMetric;
317 }
318
319 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
320 if ( !function_exists( 'getrusage' ) ) {
321 return 0;
322 }
323 $ru = getrusage();
324 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
325 if ( $metric === 'cpu' ) {
326 # This is the time of system calls, added to the user time
327 # it gives the total CPU time
328 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
329 }
330 return $time;
331 } else {
332 return microtime( true );
333 }
334 }
335
336 /**
337 * Get the initial time of the request, based either on $wgRequestTime or
338 * $wgRUstart. Will return null if not able to find data.
339 *
340 * @param string|false $metric metric to use, with the following possibilities:
341 * - user: User CPU time (without system calls)
342 * - cpu: Total CPU time (user and system calls)
343 * - wall (or any other string): elapsed time
344 * - false (default): will fall back to default metric
345 * @return float|null
346 */
347 protected function getInitialTime( $metric = false ) {
348 global $wgRequestTime, $wgRUstart;
349
350 if ( $metric === false ) {
351 $metric = $this->mTimeMetric;
352 }
353
354 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
355 if ( !count( $wgRUstart ) ) {
356 return null;
357 }
358
359 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
360 if ( $metric === 'cpu' ) {
361 # This is the time of system calls, added to the user time
362 # it gives the total CPU time
363 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
364 }
365 return $time;
366 } else {
367 if ( empty( $wgRequestTime ) ) {
368 return null;
369 } else {
370 return $wgRequestTime;
371 }
372 }
373 }
374
375 protected function collateData() {
376 if ( $this->mCollateDone ) {
377 return;
378 }
379 $this->mCollateDone = true;
380
381 $this->close();
382
383 $this->mCollated = array();
384 $this->mCalls = array();
385 $this->mMemory = array();
386
387 # Estimate profiling overhead
388 $profileCount = count( $this->mStack );
389 self::calculateOverhead( $profileCount );
390
391 # First, subtract the overhead!
392 $overheadTotal = $overheadMemory = $overheadInternal = array();
393 foreach ( $this->mStack as $entry ) {
394 $fname = $entry[0];
395 $start = $entry[2];
396 $end = $entry[4];
397 $elapsed = $end - $start;
398 $memory = $entry[5] - $entry[3];
399
400 if ( $fname == '-overhead-total' ) {
401 $overheadTotal[] = $elapsed;
402 $overheadMemory[] = $memory;
403 } elseif ( $fname == '-overhead-internal' ) {
404 $overheadInternal[] = $elapsed;
405 }
406 }
407 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
408 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
409 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
410
411 # Collate
412 foreach ( $this->mStack as $index => $entry ) {
413 $fname = $entry[0];
414 $start = $entry[2];
415 $end = $entry[4];
416 $elapsed = $end - $start;
417
418 $memory = $entry[5] - $entry[3];
419 $subcalls = $this->calltreeCount( $this->mStack, $index );
420
421 if ( !preg_match( '/^-overhead/', $fname ) ) {
422 # Adjust for profiling overhead (except special values with elapsed=0
423 if ( $elapsed ) {
424 $elapsed -= $overheadInternal;
425 $elapsed -= ($subcalls * $overheadTotal);
426 $memory -= ($subcalls * $overheadMemory);
427 }
428 }
429
430 if ( !array_key_exists( $fname, $this->mCollated ) ) {
431 $this->mCollated[$fname] = 0;
432 $this->mCalls[$fname] = 0;
433 $this->mMemory[$fname] = 0;
434 $this->mMin[$fname] = 1 << 24;
435 $this->mMax[$fname] = 0;
436 $this->mOverhead[$fname] = 0;
437 }
438
439 $this->mCollated[$fname] += $elapsed;
440 $this->mCalls[$fname]++;
441 $this->mMemory[$fname] += $memory;
442 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
443 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
444 $this->mOverhead[$fname] += $subcalls;
445 }
446
447 $this->mCalls['-overhead-total'] = $profileCount;
448 arsort( $this->mCollated, SORT_NUMERIC );
449 }
450
451 /**
452 * Returns a list of profiled functions.
453 *
454 * @return string
455 */
456 function getFunctionReport() {
457 $this->collateData();
458
459 $width = 140;
460 $nameWidth = $width - 65;
461 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
462 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
463 $prof = "\nProfiling data\n";
464 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
465
466 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
467
468 foreach ( $this->mCollated as $fname => $elapsed ) {
469 $calls = $this->mCalls[$fname];
470 $percent = $total ? 100. * $elapsed / $total : 0;
471 $memory = $this->mMemory[$fname];
472 $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] );
473 }
474 $prof .= "\nTotal: $total\n\n";
475
476 return $prof;
477 }
478
479 /**
480 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
481 */
482 protected static function calculateOverhead( $profileCount ) {
483 wfProfileIn( '-overhead-total' );
484 for ( $i = 0; $i < $profileCount; $i++ ) {
485 wfProfileIn( '-overhead-internal' );
486 wfProfileOut( '-overhead-internal' );
487 }
488 wfProfileOut( '-overhead-total' );
489 }
490
491 /**
492 * Counts the number of profiled function calls sitting under
493 * the given point in the call graph. Not the most efficient algo.
494 *
495 * @param $stack Array:
496 * @param $start Integer:
497 * @return Integer
498 * @private
499 */
500 function calltreeCount( $stack, $start ) {
501 $level = $stack[$start][1];
502 $count = 0;
503 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
504 $count ++;
505 }
506 return $count;
507 }
508
509 /**
510 * Log the whole profiling data into the database.
511 */
512 public function logData() {
513 global $wgProfilePerHost, $wgProfileToDatabase;
514
515 # Do not log anything if database is readonly (bug 5375)
516 if ( wfReadOnly() || !$wgProfileToDatabase ) {
517 return;
518 }
519
520 $dbw = wfGetDB( DB_MASTER );
521 if ( !is_object( $dbw ) ) {
522 return;
523 }
524
525 if ( $wgProfilePerHost ) {
526 $pfhost = wfHostname();
527 } else {
528 $pfhost = '';
529 }
530
531 try {
532 $this->collateData();
533
534 foreach ( $this->mCollated as $name => $elapsed ) {
535 $eventCount = $this->mCalls[$name];
536 $timeSum = (float) ($elapsed * 1000);
537 $memorySum = (float)$this->mMemory[$name];
538 $name = substr( $name, 0, 255 );
539
540 // Kludge
541 $timeSum = ($timeSum >= 0) ? $timeSum : 0;
542 $memorySum = ($memorySum >= 0) ? $memorySum : 0;
543
544 $dbw->update( 'profiling',
545 array(
546 "pf_count=pf_count+{$eventCount}",
547 "pf_time=pf_time+{$timeSum}",
548 "pf_memory=pf_memory+{$memorySum}",
549 ),
550 array(
551 'pf_name' => $name,
552 'pf_server' => $pfhost,
553 ),
554 __METHOD__ );
555
556 $rc = $dbw->affectedRows();
557 if ( $rc == 0 ) {
558 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
559 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
560 __METHOD__, array( 'IGNORE' ) );
561 }
562 // When we upgrade to mysql 4.1, the insert+update
563 // can be merged into just a insert with this construct added:
564 // "ON DUPLICATE KEY UPDATE ".
565 // "pf_count=pf_count + VALUES(pf_count), ".
566 // "pf_time=pf_time + VALUES(pf_time)";
567 }
568 } catch ( DBError $e ) {}
569 }
570
571 /**
572 * Get the function name of the current profiling section
573 * @return
574 */
575 function getCurrentSection() {
576 $elt = end( $this->mWorkStack );
577 return $elt[0];
578 }
579
580 /**
581 * Add an entry in the debug log file
582 *
583 * @param string $s to output
584 */
585 function debug( $s ) {
586 if ( defined( 'MW_COMPILED' ) || function_exists( 'wfDebug' ) ) {
587 wfDebug( $s );
588 }
589 }
590
591 /**
592 * Get the content type sent out to the client.
593 * Used for profilers that output instead of store data.
594 * @return string
595 */
596 protected function getContentType() {
597 foreach ( headers_list() as $header ) {
598 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
599 return $m[1];
600 }
601 }
602 return null;
603 }
604 }