Merge "resourceloader: Refactor empty value trimming for mw.loader.register"
[lhc/web/wiklou.git] / includes / profiler / SectionProfiler.php
1 <?php
2 /**
3 * Arbitrary section name based PHP 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 * @author Aaron Schulz
23 */
24
25 /**
26 * Custom PHP profiler for parser/DB type section names that xhprof/xdebug can't handle
27 *
28 * @since 1.25
29 */
30 class SectionProfiler {
31 /** @var array Map of (mem,real,cpu) */
32 protected $start;
33 /** @var array Map of (mem,real,cpu) */
34 protected $end;
35 /** @var array List of resolved profile calls with start/end data */
36 protected $stack = array();
37 /** @var array Queue of open profile calls with start data */
38 protected $workStack = array();
39
40 /** @var array Map of (function name => aggregate data array) */
41 protected $collated = array();
42 /** @var bool */
43 protected $collateDone = false;
44
45 /** @var bool Whether to collect the full stack trace or just aggregates */
46 protected $collateOnly = true;
47 /** @var array Cache of a standard broken collation entry */
48 protected $errorEntry;
49
50 /**
51 * @param array $params
52 */
53 public function __construct( array $params = array() ) {
54 $this->errorEntry = $this->getErrorEntry();
55 $this->collateOnly = empty( $params['trace'] );
56 }
57
58 /**
59 * @param string $section
60 * @return ScopedCallback
61 */
62 public function scopedProfileIn( $section ) {
63 $this->profileInInternal( $section );
64
65 $that = $this;
66 return new ScopedCallback( function () use ( $that, $section ) {
67 $that->profileOutInternal( $section );
68 } );
69 }
70
71 /**
72 * @param ScopedCallback $section
73 */
74 public function scopedProfileOut( ScopedCallback &$section ) {
75 $section = null;
76 }
77
78 /**
79 * Get the aggregated inclusive profiling data for each method
80 *
81 * The percent time for each time is based on the current "total" time
82 * used is based on all methods so far. This method can therefore be
83 * called several times in between several profiling calls without the
84 * delays in usage of the profiler skewing the results. A "-total" entry
85 * is always included in the results.
86 *
87 * @return array List of method entries arrays, each having:
88 * - name : method name
89 * - calls : the number of invoking calls
90 * - real : real time ellapsed (ms)
91 * - %real : percent real time
92 * - cpu : real time ellapsed (ms)
93 * - %cpu : percent real time
94 * - memory : memory used (bytes)
95 * - %memory : percent memory used
96 * - min_real : min real time in a call (ms)
97 * - max_real : max real time in a call (ms)
98 */
99 public function getFunctionStats() {
100 $this->collateData();
101
102 $totalCpu = max( $this->end['cpu'] - $this->start['cpu'], 0 );
103 $totalReal = max( $this->end['real'] - $this->start['real'], 0 );
104 $totalMem = max( $this->end['memory'] - $this->start['memory'], 0 );
105
106 $profile = array();
107 foreach ( $this->collated as $fname => $data ) {
108 $profile[] = array(
109 'name' => $fname,
110 'calls' => $data['count'],
111 'real' => $data['real'] * 1000,
112 '%real' => $totalReal ? 100 * $data['real'] / $totalReal : 0,
113 'cpu' => $data['cpu'] * 1000,
114 '%cpu' => $totalCpu ? 100 * $data['cpu'] / $totalCpu : 0,
115 'memory' => $data['memory'],
116 '%memory' => $totalMem ? 100 * $data['memory'] / $totalMem : 0,
117 'min_real' => 1000 * $data['min_real'],
118 'max_real' => 1000 * $data['max_real']
119 );
120 }
121
122 $profile[] = array(
123 'name' => '-total',
124 'calls' => 1,
125 'real' => 1000 * $totalReal,
126 '%real' => 100,
127 'cpu' => 1000 * $totalCpu,
128 '%cpu' => 100,
129 'memory' => $totalMem,
130 '%memory' => 100,
131 'min_real' => 1000 * $totalReal,
132 'max_real' => 1000 * $totalReal
133 );
134
135 return $profile;
136 }
137
138 /**
139 * Clear all of the profiling data for another run
140 */
141 public function reset() {
142 $this->start = null;
143 $this->end = null;
144 $this->stack = array();
145 $this->workStack = array();
146 $this->collated = array();
147 $this->collateDone = false;
148 }
149
150 /**
151 * @return array Initial collation entry
152 */
153 protected function getZeroEntry() {
154 return array(
155 'cpu' => 0.0,
156 'real' => 0.0,
157 'memory' => 0,
158 'count' => 0,
159 'min_real' => 0.0,
160 'max_real' => 0.0
161 );
162 }
163
164 /**
165 * @return array Initial collation entry for errors
166 */
167 protected function getErrorEntry() {
168 $entry = $this->getZeroEntry();
169 $entry['count'] = 1;
170 return $entry;
171 }
172
173 /**
174 * Update the collation entry for a given method name
175 *
176 * @param string $name
177 * @param float $elapsedCpu
178 * @param float $elapsedReal
179 * @param int $memChange
180 */
181 protected function updateEntry( $name, $elapsedCpu, $elapsedReal, $memChange ) {
182 $entry =& $this->collated[$name];
183 if ( !is_array( $entry ) ) {
184 $entry = $this->getZeroEntry();
185 $this->collated[$name] =& $entry;
186 }
187 $entry['cpu'] += $elapsedCpu;
188 $entry['real'] += $elapsedReal;
189 $entry['memory'] += $memChange > 0 ? $memChange : 0;
190 $entry['count']++;
191 $entry['min_real'] = min( $entry['min_real'], $elapsedReal );
192 $entry['max_real'] = max( $entry['max_real'], $elapsedReal );
193 }
194
195 /**
196 * This method should not be called outside SectionProfiler
197 *
198 * @param string $functionname
199 */
200 public function profileInInternal( $functionname ) {
201 // Once the data is collated for reports, any future calls
202 // should clear the collation cache so the next report will
203 // reflect them. This matters when trace mode is used.
204 $this->collateDone = false;
205
206 $cpu = $this->getTime( 'cpu' );
207 $real = $this->getTime( 'wall' );
208 $memory = memory_get_usage();
209
210 if ( $this->start === null ) {
211 $this->start = array( 'cpu' => $cpu, 'real' => $real, 'memory' => $memory );
212 }
213
214 $this->workStack[] = array(
215 $functionname,
216 count( $this->workStack ),
217 $real,
218 $cpu,
219 $memory
220 );
221 }
222
223 /**
224 * This method should not be called outside SectionProfiler
225 *
226 * @param string $functionname
227 */
228 public function profileOutInternal( $functionname ) {
229 $item = array_pop( $this->workStack );
230 if ( $item === null ) {
231 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
232 return;
233 }
234 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
235
236 if ( $functionname === 'close' ) {
237 $message = "Profile section ended by close(): {$ofname}";
238 $this->debugGroup( 'profileerror', $message );
239 if ( $this->collateOnly ) {
240 $this->collated[$message] = $this->errorEntry;
241 } else {
242 $this->stack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
243 }
244 $functionname = $ofname;
245 } elseif ( $ofname !== $functionname ) {
246 $message = "Profiling error: in({$ofname}), out($functionname)";
247 $this->debugGroup( 'profileerror', $message );
248 if ( $this->collateOnly ) {
249 $this->collated[$message] = $this->errorEntry;
250 } else {
251 $this->stack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
252 }
253 }
254
255 $realTime = $this->getTime( 'wall' );
256 $cpuTime = $this->getTime( 'cpu' );
257 $memUsage = memory_get_usage();
258
259 if ( $this->collateOnly ) {
260 $elapsedcpu = $cpuTime - $octime;
261 $elapsedreal = $realTime - $ortime;
262 $memchange = $memUsage - $omem;
263 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
264 } else {
265 $this->stack[] = array_merge( $item, array( $realTime, $cpuTime, $memUsage ) );
266 }
267
268 $this->end = array(
269 'cpu' => $cpuTime,
270 'real' => $realTime,
271 'memory' => $memUsage
272 );
273 }
274
275 /**
276 * Returns a tree of function calls with their real times
277 * @return string
278 */
279 public function getCallTreeReport() {
280 if ( $this->collateOnly ) {
281 throw new Exception( "Tree is only available for trace profiling." );
282 }
283 return implode( '', array_map(
284 array( $this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack )
285 ) );
286 }
287
288 /**
289 * Recursive function the format the current profiling array into a tree
290 *
291 * @param array $stack Profiling array
292 * @return array
293 */
294 protected function remapCallTree( array $stack ) {
295 if ( count( $stack ) < 2 ) {
296 return $stack;
297 }
298 $outputs = array();
299 for ( $max = count( $stack ) - 1; $max > 0; ) {
300 /* Find all items under this entry */
301 $level = $stack[$max][1];
302 $working = array();
303 for ( $i = $max -1; $i >= 0; $i-- ) {
304 if ( $stack[$i][1] > $level ) {
305 $working[] = $stack[$i];
306 } else {
307 break;
308 }
309 }
310 $working = $this->remapCallTree( array_reverse( $working ) );
311 $output = array();
312 foreach ( $working as $item ) {
313 array_push( $output, $item );
314 }
315 array_unshift( $output, $stack[$max] );
316 $max = $i;
317
318 array_unshift( $outputs, $output );
319 }
320 $final = array();
321 foreach ( $outputs as $output ) {
322 foreach ( $output as $item ) {
323 $final[] = $item;
324 }
325 }
326 return $final;
327 }
328
329 /**
330 * Callback to get a formatted line for the call tree
331 * @param array $entry
332 * @return string
333 */
334 protected function getCallTreeLine( $entry ) {
335 // $entry has (name, level, stime, scpu, smem, etime, ecpu, emem)
336 list( $fname, $level, $startreal, , , $endreal ) = $entry;
337 $delta = $endreal - $startreal;
338 $space = str_repeat( ' ', $level );
339 # The ugly double sprintf is to work around a PHP bug,
340 # which has been fixed in recent releases.
341 return sprintf( "%10s %s %s\n",
342 trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
343 }
344
345 /**
346 * Populate collated data
347 */
348 protected function collateData() {
349 if ( $this->collateDone ) {
350 return;
351 }
352 $this->collateDone = true;
353 // Close opened profiling sections
354 while ( count( $this->workStack ) ) {
355 $this->profileOutInternal( 'close' );
356 }
357
358 if ( $this->collateOnly ) {
359 return; // already collated as methods exited
360 }
361
362 $this->collated = array();
363
364 # Estimate profiling overhead
365 $oldEnd = $this->end;
366 $profileCount = count( $this->stack );
367 $this->calculateOverhead( $profileCount );
368
369 # First, subtract the overhead!
370 $overheadTotal = $overheadMemory = $overheadInternal = array();
371 foreach ( $this->stack as $entry ) {
372 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
373 $fname = $entry[0];
374 $elapsed = $entry[5] - $entry[2];
375 $memchange = $entry[7] - $entry[4];
376
377 if ( $fname === '-overhead-total' ) {
378 $overheadTotal[] = $elapsed;
379 $overheadMemory[] = max( 0, $memchange );
380 } elseif ( $fname === '-overhead-internal' ) {
381 $overheadInternal[] = $elapsed;
382 }
383 }
384 $overheadTotal = $overheadTotal ?
385 array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
386 $overheadMemory = $overheadMemory ?
387 array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
388 $overheadInternal = $overheadInternal ?
389 array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
390
391 # Collate
392 foreach ( $this->stack as $index => $entry ) {
393 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
394 $fname = $entry[0];
395 $elapsedCpu = $entry[6] - $entry[3];
396 $elapsedReal = $entry[5] - $entry[2];
397 $memchange = $entry[7] - $entry[4];
398 $subcalls = $this->calltreeCount( $this->stack, $index );
399
400 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
401 # Adjust for profiling overhead (except special values with elapsed=0)
402 if ( $elapsed ) {
403 $elapsed -= $overheadInternal;
404 $elapsed -= ( $subcalls * $overheadTotal );
405 $memchange -= ( $subcalls * $overheadMemory );
406 }
407 }
408
409 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange );
410 }
411
412 $this->collated['-overhead-total']['count'] = $profileCount;
413 arsort( $this->collated, SORT_NUMERIC );
414
415 // Unclobber the end info map (the overhead checking alters it)
416 $this->end = $oldEnd;
417 }
418
419 /**
420 * Dummy calls to calculate profiling overhead
421 *
422 * @param int $profileCount
423 */
424 protected function calculateOverhead( $profileCount ) {
425 $this->profileInInternal( '-overhead-total' );
426 for ( $i = 0; $i < $profileCount; $i++ ) {
427 $this->profileInInternal( '-overhead-internal' );
428 $this->profileOutInternal( '-overhead-internal' );
429 }
430 $this->profileOutInternal( '-overhead-total' );
431 }
432
433 /**
434 * Counts the number of profiled function calls sitting under
435 * the given point in the call graph. Not the most efficient algo.
436 *
437 * @param array $stack
438 * @param int $start
439 * @return int
440 */
441 protected function calltreeCount( $stack, $start ) {
442 $level = $stack[$start][1];
443 $count = 0;
444 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
445 $count ++;
446 }
447 return $count;
448 }
449
450 /**
451 * Get the initial time of the request, based either on $wgRequestTime or
452 * $wgRUstart. Will return null if not able to find data.
453 *
454 * @param string|bool $metric Metric to use, with the following possibilities:
455 * - user: User CPU time (without system calls)
456 * - cpu: Total CPU time (user and system calls)
457 * - wall (or any other string): elapsed time
458 * - false (default): will fall back to default metric
459 * @return float|null
460 */
461 protected function getTime( $metric = 'wall' ) {
462 if ( $metric === 'cpu' || $metric === 'user' ) {
463 $ru = wfGetRusage();
464 if ( !$ru ) {
465 return 0;
466 }
467 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
468 if ( $metric === 'cpu' ) {
469 # This is the time of system calls, added to the user time
470 # it gives the total CPU time
471 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
472 }
473 return $time;
474 } else {
475 return microtime( true );
476 }
477 }
478
479 /**
480 * Add an entry in the debug log file
481 *
482 * @param string $s String to output
483 */
484 protected function debug( $s ) {
485 if ( function_exists( 'wfDebug' ) ) {
486 wfDebug( $s );
487 }
488 }
489
490 /**
491 * Add an entry in the debug log group
492 *
493 * @param string $group Group to send the message to
494 * @param string $s String to output
495 */
496 protected function debugGroup( $group, $s ) {
497 if ( function_exists( 'wfDebugLog' ) ) {
498 wfDebugLog( $group, $s );
499 }
500 }
501 }