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