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
96 * - min_real : min real time in a call (ms)
97 * - max_real : max real time in a call (ms)
99 public function getFunctionStats() {
100 $this->collateData();
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 );
107 foreach ( $this->collated
as $fname => $data ) {
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']
125 'real' => 1000 * $totalReal,
127 'cpu' => 1000 * $totalCpu,
129 'memory' => $totalMem,
131 'min_real' => 1000 * $totalReal,
132 'max_real' => 1000 * $totalReal
139 * Clear all of the profiling data for another run
141 public function reset() {
144 $this->stack
= array();
145 $this->workStack
= array();
146 $this->collated
= array();
147 $this->collateDone
= false;
151 * @return array Initial collation entry
153 protected function getZeroEntry() {
165 * @return array Initial collation entry for errors
167 protected function getErrorEntry() {
168 $entry = $this->getZeroEntry();
174 * Update the collation entry for a given method name
176 * @param string $name
177 * @param float $elapsedCpu
178 * @param float $elapsedReal
179 * @param int $memChange
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;
187 $entry['cpu'] +
= $elapsedCpu;
188 $entry['real'] +
= $elapsedReal;
189 $entry['memory'] +
= $memChange > 0 ?
$memChange : 0;
191 $entry['min_real'] = min( $entry['min_real'], $elapsedReal );
192 $entry['max_real'] = max( $entry['max_real'], $elapsedReal );
196 * This method should not be called outside SectionProfiler
198 * @param string $functionname
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;
206 $cpu = $this->getTime( 'cpu' );
207 $real = $this->getTime( 'wall' );
208 $memory = memory_get_usage();
210 if ( $this->start
=== null ) {
211 $this->start
= array( 'cpu' => $cpu, 'real' => $real, 'memory' => $memory );
214 $this->workStack
[] = array(
216 count( $this->workStack
),
224 * This method should not be called outside SectionProfiler
226 * @param string $functionname
228 public function profileOutInternal( $functionname ) {
229 $item = array_pop( $this->workStack
);
230 if ( $item === null ) {
231 $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
234 list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
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
;
242 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
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
;
251 $this->stack
[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
255 $realTime = $this->getTime( 'wall' );
256 $cpuTime = $this->getTime( 'cpu' );
257 $memUsage = memory_get_usage();
259 if ( $this->collateOnly
) {
260 $elapsedcpu = $cpuTime - $octime;
261 $elapsedreal = $realTime - $ortime;
262 $memchange = $memUsage - $omem;
263 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
265 $this->stack
[] = array_merge( $item, array( $realTime, $cpuTime, $memUsage ) );
271 'memory' => $memUsage
276 * Returns a tree of function calls with their real times
279 public function getCallTreeReport() {
280 if ( $this->collateOnly
) {
281 throw new Exception( "Tree is only available for trace profiling." );
283 return implode( '', array_map(
284 array( $this, 'getCallTreeLine' ), $this->remapCallTree( $this->stack
)
289 * Recursive function the format the current profiling array into a tree
291 * @param array $stack Profiling array
294 protected function remapCallTree( array $stack ) {
295 if ( count( $stack ) < 2 ) {
299 for ( $max = count( $stack ) - 1; $max > 0; ) {
300 /* Find all items under this entry */
301 $level = $stack[$max][1];
303 for ( $i = $max -1; $i >= 0; $i-- ) {
304 if ( $stack[$i][1] > $level ) {
305 $working[] = $stack[$i];
310 $working = $this->remapCallTree( array_reverse( $working ) );
312 foreach ( $working as $item ) {
313 array_push( $output, $item );
315 array_unshift( $output, $stack[$max] );
318 array_unshift( $outputs, $output );
321 foreach ( $outputs as $output ) {
322 foreach ( $output as $item ) {
330 * Callback to get a formatted line for the call tree
331 * @param array $entry
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 );
346 * Populate collated data
348 protected function collateData() {
349 if ( $this->collateDone
) {
352 $this->collateDone
= true;
353 // Close opened profiling sections
354 while ( count( $this->workStack
) ) {
355 $this->profileOutInternal( 'close' );
358 if ( $this->collateOnly
) {
359 return; // already collated as methods exited
362 $this->collated
= array();
364 # Estimate profiling overhead
365 $oldEnd = $this->end
;
366 $profileCount = count( $this->stack
);
367 $this->calculateOverhead( $profileCount );
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)
374 $elapsed = $entry[5] - $entry[2];
375 $memchange = $entry[7] - $entry[4];
377 if ( $fname === '-overhead-total' ) {
378 $overheadTotal[] = $elapsed;
379 $overheadMemory[] = max( 0, $memchange );
380 } elseif ( $fname === '-overhead-internal' ) {
381 $overheadInternal[] = $elapsed;
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;
392 foreach ( $this->stack
as $index => $entry ) {
393 // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
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 );
400 if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
401 # Adjust for profiling overhead (except special values with elapsed=0)
403 $elapsed -= $overheadInternal;
404 $elapsed -= ( $subcalls * $overheadTotal );
405 $memchange -= ( $subcalls * $overheadMemory );
409 $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange );
412 $this->collated
['-overhead-total']['count'] = $profileCount;
413 arsort( $this->collated
, SORT_NUMERIC
);
415 // Unclobber the end info map (the overhead checking alters it)
416 $this->end
= $oldEnd;
420 * Dummy calls to calculate profiling overhead
422 * @param int $profileCount
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' );
430 $this->profileOutInternal( '-overhead-total' );
434 * Counts the number of profiled function calls sitting under
435 * the given point in the call graph. Not the most efficient algo.
437 * @param array $stack
441 protected function calltreeCount( $stack, $start ) {
442 $level = $stack[$start][1];
444 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
451 * Get the initial time of the request, based either on $wgRequestTime or
452 * $wgRUstart. Will return null if not able to find data.
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
461 protected function getTime( $metric = 'wall' ) {
462 if ( $metric === 'cpu' ||
$metric === 'user' ) {
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
;
475 return microtime( true );
480 * Add an entry in the debug log file
482 * @param string $s String to output
484 protected function debug( $s ) {
485 if ( function_exists( 'wfDebug' ) ) {
491 * Add an entry in the debug log group
493 * @param string $group Group to send the message to
494 * @param string $s String to output
496 protected function debugGroup( $group, $s ) {
497 if ( function_exists( 'wfDebugLog' ) ) {
498 wfDebugLog( $group, $s );