3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use RunningStat\RunningStat
;
24 * Convenience class for working with XHProf
25 * <https://github.com/phacility/xhprof>. XHProf can be installed as a PECL
26 * package for use with PHP5 (Zend PHP) and is built-in to HHVM 3.3.0.
28 * @author Bryan Davis <bd808@wikimedia.org>
29 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
40 * Hierarchical profiling data returned by xhprof.
41 * @var array $hieraData
46 * Per-function inclusive data.
47 * @var array $inclusive
52 * Per-function inclusive and exclusive data.
53 * @var array $complete
58 * Configuration data can contain:
59 * - flags: Optional flags to add additional information to the
60 * profiling data collected.
61 * (XHPROF_FLAGS_NO_BUILTINS, XHPROF_FLAGS_CPU,
62 * XHPROF_FLAGS_MEMORY)
63 * - exclude: Array of function names to exclude from profiling.
64 * - include: Array of function names to include in profiling.
65 * - sort: Key to sort per-function reports on.
67 * Note: When running under HHVM, xhprof will always behave as though the
68 * XHPROF_FLAGS_NO_BUILTINS flag has been used unless the
69 * Eval.JitEnableRenameFunction option is enabled for the HHVM process.
71 * @param array $config
73 public function __construct( array $config = array() ) {
74 $this->config
= array_merge(
84 xhprof_enable( $this->config
['flags'], array(
85 'ignored_functions' => $this->config
['exclude']
90 * Stop collecting profiling data.
92 * Only the first invocation of this method will effect the internal
93 * object state. Subsequent calls will return the data collected by the
96 * @return array Collected profiling data (possibly cached)
98 public function stop() {
99 if ( $this->hieraData
=== null ) {
100 $this->hieraData
= $this->pruneData( xhprof_disable() );
102 return $this->hieraData
;
106 * Load raw data from a prior run for analysis.
107 * Stops any existing data collection and clears internal caches.
109 * Any 'include' filters configured for this Xhprof instance will be
110 * enforced on the data as it is loaded. 'exclude' filters will however
111 * not be enforced as they are an XHProf intrinsic behavior.
116 public function loadRawData( array $data ) {
118 $this->inclusive
= null;
119 $this->complete
= null;
120 $this->hieraData
= $this->pruneData( $data );
124 * Get raw data collected by xhprof.
126 * If data collection has not been stopped yet this method will halt
127 * collection to gather the profiling data.
129 * Each key in the returned array is an edge label for the call graph in
130 * the form "caller==>callee". There is once special case edge labled
131 * simply "main()" which represents the global scope entry point of the
134 * XHProf will collect different data depending on the flags that are used:
135 * - ct: Number of matching events seen.
136 * - wt: Inclusive elapsed wall time for this event in microseconds.
137 * - cpu: Inclusive elapsed cpu time for this event in microseconds.
139 * - mu: Delta of memory usage from start to end of callee in bytes.
140 * (XHPROF_FLAGS_MEMORY)
141 * - pmu: Delta of peak memory usage from start to end of callee in
142 * bytes. (XHPROF_FLAGS_MEMORY)
143 * - alloc: Delta of amount memory requested from malloc() by the callee,
144 * in bytes. (XHPROF_FLAGS_MALLOC)
145 * - free: Delta of amount of memory passed to free() by the callee, in
146 * bytes. (XHPROF_FLAGS_MALLOC)
150 * @see getInclusiveMetrics()
151 * @see getCompleteMetrics()
153 public function getRawData() {
154 return $this->stop();
158 * Convert an xhprof data key into an array of ['parent', 'child']
161 * The resulting array is left padded with nulls, so a key
162 * with no parent (eg 'main()') will return [null, 'function'].
166 public static function splitKey( $key ) {
167 return array_pad( explode( '==>', $key, 2 ), -2, null );
171 * Remove data for functions that are not included in the 'include'
172 * configuration array.
174 * @param array $data Raw xhprof data
177 protected function pruneData( $data ) {
178 if ( !$this->config
['include'] ) {
182 $want = array_fill_keys( $this->config
['include'], true );
183 $want['main()'] = true;
186 foreach ( $data as $key => $stats ) {
187 list( $parent, $child ) = self
::splitKey( $key );
188 if ( isset( $want[$parent] ) ||
isset( $want[$child] ) ) {
189 $keep[$key] = $stats;
196 * Get the inclusive metrics for each function call. Inclusive metrics
197 * for given function include the metrics for all functions that were
198 * called from that function during the measurement period.
200 * If data collection has not been stopped yet this method will halt
201 * collection to gather the profiling data.
203 * See getRawData() for a description of the metric that are returned for
204 * each funcition call. The values for the wt, cpu, mu and pmu metrics are
205 * arrays with these values:
206 * - total: Cumulative value
207 * - min: Minimum value
208 * - mean: Mean (average) value
209 * - max: Maximum value
210 * - variance: Variance (spread) of the values
214 * @see getCompleteMetrics()
216 public function getInclusiveMetrics() {
217 if ( $this->inclusive
=== null ) {
218 // Make sure we have data to work with
221 $main = $this->hieraData
['main()'];
222 $hasCpu = isset( $main['cpu'] );
223 $hasMu = isset( $main['mu'] );
224 $hasAlloc = isset( $main['alloc'] );
226 $this->inclusive
= array();
227 foreach ( $this->hieraData
as $key => $stats ) {
228 list( $parent, $child ) = self
::splitKey( $key );
229 if ( !isset( $this->inclusive
[$child] ) ) {
230 $this->inclusive
[$child] = array(
232 'wt' => new RunningStat(),
235 $this->inclusive
[$child]['cpu'] = new RunningStat();
238 $this->inclusive
[$child]['mu'] = new RunningStat();
239 $this->inclusive
[$child]['pmu'] = new RunningStat();
242 $this->inclusive
[$child]['alloc'] = new RunningStat();
243 $this->inclusive
[$child]['free'] = new RunningStat();
247 $this->inclusive
[$child]['ct'] +
= $stats['ct'];
248 foreach ( $stats as $stat => $value ) {
249 if ( $stat === 'ct' ) {
253 if ( !isset( $this->inclusive
[$child][$stat] ) ) {
254 // Ignore unknown stats
258 for ( $i = 0; $i < $stats['ct']; $i++
) {
259 $this->inclusive
[$child][$stat]->addObservation(
260 $value / $stats['ct']
266 // Convert RunningStat instances to static arrays and add
268 foreach ( $this->inclusive
as $func => $stats ) {
269 foreach ( $stats as $name => $value ) {
270 if ( $value instanceof RunningStat
) {
271 $total = $value->m1
* $value->n
;
272 $percent = ( isset( $main[$name] ) && $main[$name] )
273 ?
100 * $total / $main[$name]
275 $this->inclusive
[$func][$name] = array(
277 'min' => $value->min
,
278 'mean' => $value->m1
,
279 'max' => $value->max
,
280 'variance' => $value->m2
,
281 'percent' => $percent,
287 uasort( $this->inclusive
, self
::makeSortFunction(
288 $this->config
['sort'], 'total'
291 return $this->inclusive
;
295 * Get the inclusive and exclusive metrics for each function call.
297 * If data collection has not been stopped yet this method will halt
298 * collection to gather the profiling data.
300 * In addition to the normal data contained in the inclusive metrics, the
301 * metrics have an additional 'exclusive' measurement which is the total
302 * minus the totals of all child function calls.
306 * @see getInclusiveMetrics()
308 public function getCompleteMetrics() {
309 if ( $this->complete
=== null ) {
310 // Start with inclusive data
311 $this->complete
= $this->getInclusiveMetrics();
313 foreach ( $this->complete
as $func => $stats ) {
314 foreach ( $stats as $stat => $value ) {
315 if ( $stat === 'ct' ) {
318 // Initialize exclusive data with inclusive totals
319 $this->complete
[$func][$stat]['exclusive'] = $value['total'];
321 // Add sapce for call tree information to be filled in later
322 $this->complete
[$func]['calls'] = array();
323 $this->complete
[$func]['subcalls'] = array();
326 foreach ( $this->hieraData
as $key => $stats ) {
327 list( $parent, $child ) = self
::splitKey( $key );
328 if ( $parent !== null ) {
329 // Track call tree information
330 $this->complete
[$child]['calls'][$parent] = $stats;
331 $this->complete
[$parent]['subcalls'][$child] = $stats;
334 if ( isset( $this->complete
[$parent] ) ) {
335 // Deduct child inclusive data from exclusive data
336 foreach ( $stats as $stat => $value ) {
337 if ( $stat === 'ct' ) {
341 if ( !isset( $this->complete
[$parent][$stat] ) ) {
342 // Ignore unknown stats
346 $this->complete
[$parent][$stat]['exclusive'] -= $value;
351 uasort( $this->complete
, self
::makeSortFunction(
352 $this->config
['sort'], 'exclusive'
355 return $this->complete
;
359 * Get a list of all callers of a given function.
361 * @param string $function Function name
365 public function getCallers( $function ) {
366 $edges = $this->getCompleteMetrics();
367 if ( isset( $edges[$function]['calls'] ) ) {
368 return array_keys( $edges[$function]['calls'] );
375 * Get a list of all callees from a given function.
377 * @param string $function Function name
381 public function getCallees( $function ) {
382 $edges = $this->getCompleteMetrics();
383 if ( isset( $edges[$function]['subcalls'] ) ) {
384 return array_keys( $edges[$function]['subcalls'] );
391 * Find the critical path for the given metric.
393 * @param string $metric Metric to find critical path for
396 public function getCriticalPath( $metric = 'wt' ) {
400 $func => $this->hieraData
[$func],
403 $callees = $this->getCallees( $func );
406 foreach ( $callees as $callee ) {
407 $call = "{$func}==>{$callee}";
408 if ( $maxCall === null ||
409 $this->hieraData
[$call][$metric] >
410 $this->hieraData
[$maxCall][$metric]
412 $maxCallee = $callee;
416 if ( $maxCall !== null ) {
417 $path[$maxCall] = $this->hieraData
[$maxCall];
425 * Make a closure to use as a sort function. The resulting function will
426 * sort by descending numeric values (largest value first).
428 * @param string $key Data key to sort on
429 * @param string $sub Sub key to sort array values on
432 public static function makeSortFunction( $key, $sub ) {
433 return function ( $a, $b ) use ( $key, $sub ) {
434 if ( isset( $a[$key] ) && isset( $b[$key] ) ) {
435 // Descending sort: larger values will be first in result.
436 // Assumes all values are numeric.
437 // Values for 'main()' will not have sub keys
438 $valA = is_array( $a[$key] ) ?
$a[$key][$sub] : $a[$key];
439 $valB = is_array( $b[$key] ) ?
$b[$key][$sub] : $b[$key];
440 return $valB - $valA;
442 // Sort datum with the key before those without
443 return isset( $a[$key] ) ?
-1 : 1;