1ad01ccc9fc721a0e49aa8fef98f70712a5a14db
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
23 * Convenience class for working with XHProf
24 * <https://github.com/phacility/xhprof>. XHProf can be installed as a PECL
25 * package for use with PHP5 (Zend PHP) and is built-in to HHVM 3.3.0.
27 * @author Bryan Davis <bd808@wikimedia.org>
28 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
39 * Hierarchical profiling data returned by xhprof.
40 * @var array $hieraData
45 * Per-function inclusive data.
46 * @var array $inclusive
51 * Per-function inclusive and exclusive data.
52 * @var array $complete
57 * Configuration data can contain:
58 * - flags: Optional flags to add additional information to the
59 * profiling data collected.
60 * (XHPROF_FLAGS_NO_BUILTINS, XHPROF_FLAGS_CPU,
61 * XHPROF_FLAGS_MEMORY)
62 * - exclude: Array of function names to exclude from profiling.
63 * - include: Array of function names to include in profiling.
64 * - sort: Key to sort per-function reports on.
66 * Note: When running under HHVM, xhprof will always behave as though the
67 * XHPROF_FLAGS_NO_BUILTINS flag has been used unless the
68 * Eval.JitEnableRenameFunction option is enabled for the HHVM process.
70 * @param array $config
72 public function __construct( array $config = array() ) {
73 $this->config
= array_merge(
83 xhprof_enable( $this->config
['flags'], array(
84 'ignored_functions' => $this->config
['exclude']
89 * Stop collecting profiling data.
91 * Only the first invocation of this method will effect the internal
92 * object state. Subsequent calls will return the data collected by the
95 * @return array Collected profiling data (possibly cached)
97 public function stop() {
98 if ( $this->hieraData
=== null ) {
99 $this->hieraData
= $this->pruneData( xhprof_disable() );
101 return $this->hieraData
;
105 * Load raw data from a prior run for analysis.
106 * Stops any existing data collection and clears internal caches.
108 * Any 'include' filters configured for this Xhprof instance will be
109 * enforced on the data as it is loaded. 'exclude' filters will however
110 * not be enforced as they are an XHProf intrinsic behavior.
115 public function loadRawData( array $data ) {
117 $this->inclusive
= null;
118 $this->complete
= null;
119 $this->hieraData
= $this->pruneData( $data );
123 * Get raw data collected by xhprof.
125 * If data collection has not been stopped yet this method will halt
126 * collection to gather the profiling data.
128 * Each key in the returned array is an edge label for the call graph in
129 * the form "caller==>callee". There is once special case edge labled
130 * simply "main()" which represents the global scope entry point of the
133 * XHProf will collect different data depending on the flags that are used:
134 * - ct: Number of matching events seen.
135 * - wt: Inclusive elapsed wall time for this event in microseconds.
136 * - cpu: Inclusive elapsed cpu time for this event in microseconds.
138 * - mu: Delta of memory usage from start to end of callee in bytes.
139 * (XHPROF_FLAGS_MEMORY)
140 * - pmu: Delta of peak memory usage from start to end of callee in
141 * bytes. (XHPROF_FLAGS_MEMORY)
142 * - alloc: Delta of amount memory requested from malloc() by the callee,
143 * in bytes. (XHPROF_FLAGS_MALLOC)
144 * - free: Delta of amount of memory passed to free() by the callee, in
145 * bytes. (XHPROF_FLAGS_MALLOC)
149 * @see getInclusiveMetrics()
150 * @see getCompleteMetrics()
152 public function getRawData() {
153 return $this->stop();
157 * Convert an xhprof data key into an array of ['parent', 'child']
160 * The resulting array is left padded with nulls, so a key
161 * with no parent (eg 'main()') will return [null, 'function'].
165 public static function splitKey( $key ) {
166 return array_pad( explode( '==>', $key, 2 ), -2, null );
170 * Remove data for functions that are not included in the 'include'
171 * configuration array.
173 * @param array $data Raw xhprof data
176 protected function pruneData( $data ) {
177 if ( !$this->config
['include'] ) {
181 $want = array_fill_keys( $this->config
['include'], true );
182 $want['main()'] = true;
185 foreach ( $data as $key => $stats ) {
186 list( $parent, $child ) = self
::splitKey( $key );
187 if ( isset( $want[$parent] ) ||
isset( $want[$child] ) ) {
188 $keep[$key] = $stats;
195 * Get the inclusive metrics for each function call. Inclusive metrics
196 * for given function include the metrics for all functions that were
197 * called from that function during the measurement period.
199 * If data collection has not been stopped yet this method will halt
200 * collection to gather the profiling data.
202 * See getRawData() for a description of the metric that are returned for
203 * each funcition call. The values for the wt, cpu, mu and pmu metrics are
204 * arrays with these values:
205 * - total: Cumulative value
206 * - min: Minimum value
207 * - mean: Mean (average) value
208 * - max: Maximum value
209 * - variance: Variance (spread) of the values
213 * @see getCompleteMetrics()
215 public function getInclusiveMetrics() {
216 if ( $this->inclusive
=== null ) {
217 // Make sure we have data to work with
220 $main = $this->hieraData
['main()'];
221 $hasCpu = isset( $main['cpu'] );
222 $hasMu = isset( $main['mu'] );
223 $hasAlloc = isset( $main['alloc'] );
225 $this->inclusive
= array();
226 foreach ( $this->hieraData
as $key => $stats ) {
227 list( $parent, $child ) = self
::splitKey( $key );
228 if ( !isset( $this->inclusive
[$child] ) ) {
229 $this->inclusive
[$child] = array(
231 'wt' => new RunningStat(),
234 $this->inclusive
[$child]['cpu'] = new RunningStat();
237 $this->inclusive
[$child]['mu'] = new RunningStat();
238 $this->inclusive
[$child]['pmu'] = new RunningStat();
241 $this->inclusive
[$child]['alloc'] = new RunningStat();
242 $this->inclusive
[$child]['free'] = new RunningStat();
246 $this->inclusive
[$child]['ct'] +
= $stats['ct'];
247 foreach ( $stats as $stat => $value ) {
248 if ( $stat === 'ct' ) {
252 if ( !isset( $this->inclusive
[$child][$stat] ) ) {
253 // Ignore unknown stats
257 for ( $i = 0; $i < $stats['ct']; $i++
) {
258 $this->inclusive
[$child][$stat]->push(
259 $value / $stats['ct']
265 // Convert RunningStat instances to static arrays and add
267 foreach ( $this->inclusive
as $func => $stats ) {
268 foreach ( $stats as $name => $value ) {
269 if ( $value instanceof RunningStat
) {
270 $total = $value->m1
* $value->n
;
271 $this->inclusive
[$func][$name] = array(
273 'min' => $value->min
,
274 'mean' => $value->m1
,
275 'max' => $value->max
,
276 'variance' => $value->m2
,
277 'percent' => 100 * $total / $main[$name],
283 uasort( $this->inclusive
, self
::makeSortFunction(
284 $this->config
['sort'], 'total'
287 return $this->inclusive
;
291 * Get the inclusive and exclusive metrics for each function call.
293 * If data collection has not been stopped yet this method will halt
294 * collection to gather the profiling data.
296 * In addition to the normal data contained in the inclusive metrics, the
297 * metrics have an additional 'exclusive' measurement which is the total
298 * minus the totals of all child function calls.
302 * @see getInclusiveMetrics()
304 public function getCompleteMetrics() {
305 if ( $this->complete
=== null ) {
306 // Start with inclusive data
307 $this->complete
= $this->getInclusiveMetrics();
309 foreach ( $this->complete
as $func => $stats ) {
310 foreach ( $stats as $stat => $value ) {
311 if ( $stat === 'ct' ) {
314 // Initialize exclusive data with inclusive totals
315 $this->complete
[$func][$stat]['exclusive'] = $value['total'];
317 // Add sapce for call tree information to be filled in later
318 $this->complete
[$func]['calls'] = array();
319 $this->complete
[$func]['subcalls'] = array();
322 foreach( $this->hieraData
as $key => $stats ) {
323 list( $parent, $child ) = self
::splitKey( $key );
324 if ( $parent !== null ) {
325 // Track call tree information
326 $this->complete
[$child]['calls'][$parent] = $stats;
327 $this->complete
[$parent]['subcalls'][$child] = $stats;
330 if ( isset( $this->complete
[$parent] ) ) {
331 // Deduct child inclusive data from exclusive data
332 foreach ( $stats as $stat => $value ) {
333 if ( $stat === 'ct' ) {
337 if ( !isset( $this->complete
[$parent][$stat] ) ) {
338 // Ignore unknown stats
342 $this->complete
[$parent][$stat]['exclusive'] -= $value;
347 uasort( $this->complete
, self
::makeSortFunction(
348 $this->config
['sort'], 'exclusive'
351 return $this->complete
;
355 * Get a list of all callers of a given function.
357 * @param string $function Function name
361 public function getCallers( $function ) {
362 $edges = $this->getCompleteMetrics();
363 if ( isset( $edges[$function]['calls'] ) ) {
364 return array_keys( $edges[$function]['calls'] );
371 * Get a list of all callees from a given function.
373 * @param string $function Function name
377 public function getCallees( $function ) {
378 $edges = $this->getCompleteMetrics();
379 if ( isset( $edges[$function]['subcalls'] ) ) {
380 return array_keys( $edges[$function]['subcalls'] );
387 * Find the critical path for the given metric.
389 * @param string $metric Metric to find critical path for
392 public function getCriticalPath( $metric = 'wt' ) {
396 $func => $this->hieraData
[$func],
399 $callees = $this->getCallees( $func );
402 foreach ( $callees as $callee ) {
403 $call = "{$func}==>{$callee}";
404 if ( $maxCall === null ||
405 $this->hieraData
[$call][$metric] >
406 $this->hieraData
[$maxCall][$metric]
408 $maxCallee = $callee;
412 if ( $maxCall !== null ) {
413 $path[$maxCall] = $this->hieraData
[$maxCall];
421 * Make a closure to use as a sort function. The resulting function will
422 * sort by descending numeric values (largest value first).
424 * @param string $key Data key to sort on
425 * @param string $sub Sub key to sort array values on
428 public static function makeSortFunction( $key, $sub ) {
429 return function ( $a, $b ) use ( $key, $sub ) {
430 if ( isset( $a[$key] ) && isset( $b[$key] ) ) {
431 // Descending sort: larger values will be first in result.
432 // Assumes all values are numeric.
433 // Values for 'main()' will not have sub keys
434 $valA = is_array( $a[$key] ) ?
$a[$key][$sub] : $a[$key];
435 $valB = is_array( $b[$key] ) ?
$b[$key][$sub] : $b[$key];
436 return $valB - $valA;
438 // Sort datum with the key before those without
439 return isset( $a[$key] ) ?
-1 : 1;