3 * Arbitrary section name based PHP profiling.
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.
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.
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
22 * @author Aaron Schulz
26 * Custom PHP profiler for parser/DB type section names that xhprof/xdebug can't handle
30 class SectionProfiler
{
31 /** @var array Map of (mem,real,cpu) */
33 /** @var array Map of (mem,real,cpu) */
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();
40 /** @var array Map of (function name => aggregate data array) */
41 protected $collated = array();
43 protected $collateDone = false;
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;
51 * @param array $params
53 public function __construct( array $params = array() ) {
54 $this->errorEntry
= $this->getErrorEntry();
55 $this->collateOnly
= empty( $params['trace'] );
59 * @param string $section
60 * @return ScopedCallback
62 public function scopedProfileIn( $section ) {
63 $this->profileInInternal( $section );
66 return new ScopedCallback( function () use ( $that, $section ) {
67 $that->profileOutInternal( $section );
72 * @param ScopedCallback $section
74 public function scopedProfileOut( ScopedCallback
&$section ) {
79 * Get the aggregated inclusive profiling data for each method
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.
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
97 public function getFunctionStats() {
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 );
105 foreach ( $this->collated
as $fname => $data ) {
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,
121 'real' => 1000 * $totalReal,
123 'cpu' => 1000 * $totalCpu,
125 'memory' => $totalMem,
133 * Clear all of the profiling data for another run
135 public function reset() {
138 $this->stack
= array();
139 $this->workStack
= array();
140 $this->collated
= array();
141 $this->collateDone
= false;
145 * @return array Initial collation entry
147 protected function getZeroEntry() {
157 * @return array Initial collation entry for errors
159 protected function getErrorEntry() {
160 $entry = $this->getZeroEntry();
166 * Update the collation entry for a given method name
168 * @param string $name
169 * @param float $elapsedCpu
170 * @param float $elapsedReal
171 * @param int $memChange
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;
179 $entry['cpu'] +
= $elapsedCpu;
180 $entry['real'] +
= $elapsedReal;
181 $entry['memory'] +
= $memChange > 0 ?
$memChange : 0;
186 * This method should not be called outside SectionProfiler
188 * @param string $functionname
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;
196 $cpu = $this->getTime( 'cpu' );
197 $real = $this->getTime( 'wall' );
198 $memory = memory_get_usage();
200 if ( $this->start
=== null ) {
201 $this->start
= array( 'cpu' => $cpu, 'real' => $real, 'memory' => $memory );
204 $this->workStack
[] = array(
206 count( $this->workStack
),
214 * This method should not be called outside SectionProfiler
216 * @param string $functionname
218 public function profileOutInternal( $functionname ) {
219 $item = array_pop( $this->workStack
);
220 if ( $item === null ) {
221 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
224 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
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
;
232 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
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
;
241 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
245 $realTime = $this->getTime( 'wall' );
246 $cpuTime = $this->getTime( 'cpu' );
247 $memUsage = memory_get_usage();
249 if ( $this->collateOnly
) {
250 $elapsedcpu = $cpuTime - $octime;
251 $elapsedreal = $realTime - $ortime;
252 $memchange = $memUsage - $omem;
253 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
255 $this->stack
[] = array_merge( $item, array( $realTime, $cpuTime, $memUsage ) );
261 'memory' => $memUsage
266 * Returns a tree of function calls with their real times
269 public function getCallTreeReport() {
270 if ( $this->collateOnly
) {
271 throw new Exception( "Tree is only available for trace profiling." );
273 return implode( '', array_map(
274 array( $this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack
)
279 * Recursive function the format the current profiling array into a tree
281 * @param array $stack Profiling array
284 protected function remapCallTree( array $stack ) {
285 if ( count( $stack ) < 2 ) {
289 for ( $max = count( $stack ) - 1; $max > 0; ) {
290 /* Find all items under this entry */
291 $level = $stack[$max][1];
293 for ( $i = $max -1; $i >= 0; $i-- ) {
294 if ( $stack[$i][1] > $level ) {
295 $working[] = $stack[$i];
300 $working = $this->remapCallTree( array_reverse( $working ) );
302 foreach ( $working as $item ) {
303 array_push( $output, $item );
305 array_unshift( $output, $stack[$max] );
308 array_unshift( $outputs, $output );
311 foreach ( $outputs as $output ) {
312 foreach ( $output as $item ) {
320 * Callback to get a formatted line for the call tree
321 * @param array $entry
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 );
336 * Populate collated data
338 protected function collateData() {
339 if ( $this->collateDone
) {
342 $this->collateDone
= true;
343 // Close opened profiling sections
344 while ( count( $this->workStack
) ) {
345 $this->profileOutInternal( 'close' );
348 if ( $this->collateOnly
) {
349 return; // already collated as methods exited
352 $this->collated
= array();
354 # Estimate profiling overhead
355 $oldEnd = $this->end
;
356 $profileCount = count( $this->stack
);
357 $this->calculateOverhead( $profileCount );
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)
364 $elapsed = $entry[5] - $entry[2];
365 $memchange = $entry[7] - $entry[4];
367 if ( $fname === '-overhead-total' ) {
368 $overheadTotal[] = $elapsed;
369 $overheadMemory[] = max( 0, $memchange );
370 } elseif ( $fname === '-overhead-internal' ) {
371 $overheadInternal[] = $elapsed;
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;
382 foreach ( $this->stack
as $index => $entry ) {
383 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
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 );
390 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
391 # Adjust for profiling overhead (except special values with elapsed=0)
393 $elapsed -= $overheadInternal;
394 $elapsed -= ( $subcalls * $overheadTotal );
395 $memchange -= ( $subcalls * $overheadMemory );
399 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange );
402 $this->collated
['-overhead-total']['count'] = $profileCount;
403 arsort( $this->collated
, SORT_NUMERIC
);
405 // Unclobber the end info map (the overhead checking alters it)
406 $this->end
= $oldEnd;
410 * Dummy calls to calculate profiling overhead
412 * @param int $profileCount
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' );
420 $this->profileOutInternal( '-overhead-total' );
424 * Counts the number of profiled function calls sitting under
425 * the given point in the call graph. Not the most efficient algo.
427 * @param array $stack
431 protected function calltreeCount( $stack, $start ) {
432 $level = $stack[$start][1];
434 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
441 * Get the initial time of the request, based either on $wgRequestTime or
442 * $wgRUstart. Will return null if not able to find data.
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
451 protected function getTime( $metric = 'wall' ) {
452 if ( $metric === 'cpu' ||
$metric === 'user' ) {
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
;
465 return microtime( true );
470 * Add an entry in the debug log file
472 * @param string $s String to output
474 protected function debug( $s ) {
475 if ( function_exists( 'wfDebug' ) ) {
481 * Add an entry in the debug log group
483 * @param string $group Group to send the message to
484 * @param string $s String to output
486 protected function debugGroup( $group, $s ) {
487 if ( function_exists( 'wfDebugLog' ) ) {
488 wfDebugLog( $group, $s );