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