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 profiling data
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 * @copyright © 2014 Wikimedia Foundation and contributors
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 * - include: Array of function names to include in profiling.
59 * - sort: Key to sort per-function reports on.
61 * @param array $data Xhprof profiling data, as returned by xhprof_disable()
62 * @param array $config
64 public function __construct( array $data, array $config = [] ) {
65 $this->config
= array_merge( [
70 $this->hieraData
= $this->pruneData( $data );
74 * Get raw data collected by xhprof.
76 * Each key in the returned array is an edge label for the call graph in
77 * the form "caller==>callee". There is once special case edge labled
78 * simply "main()" which represents the global scope entry point of the
81 * XHProf will collect different data depending on the flags that are used:
82 * - ct: Number of matching events seen.
83 * - wt: Inclusive elapsed wall time for this event in microseconds.
84 * - cpu: Inclusive elapsed cpu time for this event in microseconds.
86 * - mu: Delta of memory usage from start to end of callee in bytes.
87 * (XHPROF_FLAGS_MEMORY)
88 * - pmu: Delta of peak memory usage from start to end of callee in
89 * bytes. (XHPROF_FLAGS_MEMORY)
90 * - alloc: Delta of amount memory requested from malloc() by the callee,
91 * in bytes. (XHPROF_FLAGS_MALLOC)
92 * - free: Delta of amount of memory passed to free() by the callee, in
93 * bytes. (XHPROF_FLAGS_MALLOC)
96 * @see getInclusiveMetrics()
97 * @see getCompleteMetrics()
99 public function getRawData() {
100 return $this->hieraData
;
104 * Convert an xhprof data key into an array of ['parent', 'child']
107 * The resulting array is left padded with nulls, so a key
108 * with no parent (eg 'main()') will return [null, 'function'].
112 public static function splitKey( $key ) {
113 return array_pad( explode( '==>', $key, 2 ), -2, null );
117 * Remove data for functions that are not included in the 'include'
118 * configuration array.
120 * @param array $data Raw xhprof data
123 protected function pruneData( $data ) {
124 if ( !$this->config
['include'] ) {
128 $want = array_fill_keys( $this->config
['include'], true );
129 $want['main()'] = true;
132 foreach ( $data as $key => $stats ) {
133 list( $parent, $child ) = self
::splitKey( $key );
134 if ( isset( $want[$parent] ) ||
isset( $want[$child] ) ) {
135 $keep[$key] = $stats;
142 * Get the inclusive metrics for each function call. Inclusive metrics
143 * for given function include the metrics for all functions that were
144 * called from that function during the measurement period.
146 * See getRawData() for a description of the metric that are returned for
147 * each funcition call. The values for the wt, cpu, mu and pmu metrics are
148 * arrays with these values:
149 * - total: Cumulative value
150 * - min: Minimum value
151 * - mean: Mean (average) value
152 * - max: Maximum value
153 * - variance: Variance (spread) of the values
157 * @see getCompleteMetrics()
159 public function getInclusiveMetrics() {
160 if ( $this->inclusive
=== null ) {
161 $main = $this->hieraData
['main()'];
162 $hasCpu = isset( $main['cpu'] );
163 $hasMu = isset( $main['mu'] );
164 $hasAlloc = isset( $main['alloc'] );
166 $this->inclusive
= [];
167 foreach ( $this->hieraData
as $key => $stats ) {
168 list( $parent, $child ) = self
::splitKey( $key );
169 if ( !isset( $this->inclusive
[$child] ) ) {
170 $this->inclusive
[$child] = [
172 'wt' => new RunningStat(),
175 $this->inclusive
[$child]['cpu'] = new RunningStat();
178 $this->inclusive
[$child]['mu'] = new RunningStat();
179 $this->inclusive
[$child]['pmu'] = new RunningStat();
182 $this->inclusive
[$child]['alloc'] = new RunningStat();
183 $this->inclusive
[$child]['free'] = new RunningStat();
187 $this->inclusive
[$child]['ct'] +
= $stats['ct'];
188 foreach ( $stats as $stat => $value ) {
189 if ( $stat === 'ct' ) {
193 if ( !isset( $this->inclusive
[$child][$stat] ) ) {
194 // Ignore unknown stats
198 for ( $i = 0; $i < $stats['ct']; $i++
) {
199 $this->inclusive
[$child][$stat]->addObservation(
200 $value / $stats['ct']
206 // Convert RunningStat instances to static arrays and add
208 foreach ( $this->inclusive
as $func => $stats ) {
209 foreach ( $stats as $name => $value ) {
210 if ( $value instanceof RunningStat
) {
211 $total = $value->m1
* $value->n
;
212 $percent = ( isset( $main[$name] ) && $main[$name] )
213 ?
100 * $total / $main[$name]
215 $this->inclusive
[$func][$name] = [
217 'min' => $value->min
,
218 'mean' => $value->m1
,
219 'max' => $value->max
,
220 'variance' => $value->m2
,
221 'percent' => $percent,
227 uasort( $this->inclusive
, self
::makeSortFunction(
228 $this->config
['sort'], 'total'
231 return $this->inclusive
;
235 * Get the inclusive and exclusive metrics for each function call.
237 * In addition to the normal data contained in the inclusive metrics, the
238 * metrics have an additional 'exclusive' measurement which is the total
239 * minus the totals of all child function calls.
243 * @see getInclusiveMetrics()
245 public function getCompleteMetrics() {
246 if ( $this->complete
=== null ) {
247 // Start with inclusive data
248 $this->complete
= $this->getInclusiveMetrics();
250 foreach ( $this->complete
as $func => $stats ) {
251 foreach ( $stats as $stat => $value ) {
252 if ( $stat === 'ct' ) {
255 // Initialize exclusive data with inclusive totals
256 $this->complete
[$func][$stat]['exclusive'] = $value['total'];
258 // Add sapce for call tree information to be filled in later
259 $this->complete
[$func]['calls'] = [];
260 $this->complete
[$func]['subcalls'] = [];
263 foreach ( $this->hieraData
as $key => $stats ) {
264 list( $parent, $child ) = self
::splitKey( $key );
265 if ( $parent !== null ) {
266 // Track call tree information
267 $this->complete
[$child]['calls'][$parent] = $stats;
268 $this->complete
[$parent]['subcalls'][$child] = $stats;
271 if ( isset( $this->complete
[$parent] ) ) {
272 // Deduct child inclusive data from exclusive data
273 foreach ( $stats as $stat => $value ) {
274 if ( $stat === 'ct' ) {
278 if ( !isset( $this->complete
[$parent][$stat] ) ) {
279 // Ignore unknown stats
283 $this->complete
[$parent][$stat]['exclusive'] -= $value;
288 uasort( $this->complete
, self
::makeSortFunction(
289 $this->config
['sort'], 'exclusive'
292 return $this->complete
;
296 * Get a list of all callers of a given function.
298 * @param string $function Function name
302 public function getCallers( $function ) {
303 $edges = $this->getCompleteMetrics();
304 if ( isset( $edges[$function]['calls'] ) ) {
305 return array_keys( $edges[$function]['calls'] );
312 * Get a list of all callees from a given function.
314 * @param string $function Function name
318 public function getCallees( $function ) {
319 $edges = $this->getCompleteMetrics();
320 if ( isset( $edges[$function]['subcalls'] ) ) {
321 return array_keys( $edges[$function]['subcalls'] );
328 * Find the critical path for the given metric.
330 * @param string $metric Metric to find critical path for
333 public function getCriticalPath( $metric = 'wt' ) {
336 $func => $this->hieraData
[$func],
339 $callees = $this->getCallees( $func );
342 foreach ( $callees as $callee ) {
343 $call = "{$func}==>{$callee}";
344 if ( $maxCall === null ||
345 $this->hieraData
[$call][$metric] >
346 $this->hieraData
[$maxCall][$metric]
348 $maxCallee = $callee;
352 if ( $maxCall !== null ) {
353 $path[$maxCall] = $this->hieraData
[$maxCall];
361 * Make a closure to use as a sort function. The resulting function will
362 * sort by descending numeric values (largest value first).
364 * @param string $key Data key to sort on
365 * @param string $sub Sub key to sort array values on
368 public static function makeSortFunction( $key, $sub ) {
369 return function ( $a, $b ) use ( $key, $sub ) {
370 if ( isset( $a[$key] ) && isset( $b[$key] ) ) {
371 // Descending sort: larger values will be first in result.
372 // Assumes all values are numeric.
373 // Values for 'main()' will not have sub keys
374 $valA = is_array( $a[$key] ) ?
$a[$key][$sub] : $a[$key];
375 $valB = is_array( $b[$key] ) ?
$b[$key][$sub] : $b[$key];
376 return $valB - $valA;
378 // Sort datum with the key before those without
379 return isset( $a[$key] ) ?
-1 : 1;