Make ApiStashEdit use the StashEdit log group, rather than PreparedEdit
[mediawiki.git] / includes / libs / Xhprof.php
blob990e2c30533be49547baa040591a4b58613cc81c
1 <?php
2 /**
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
18 * @file
21 /**
22 * Convenience class for working with XHProf
23 * <https://github.com/phacility/xhprof>. XHProf can be installed as a PECL
24 * package for use with PHP5 (Zend PHP) and is built-in to HHVM 3.3.0.
26 * @author Bryan Davis <bd808@wikimedia.org>
27 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
28 * @since 1.25
30 class Xhprof {
32 /**
33 * @var array $config
35 protected $config;
37 /**
38 * Hierarchical profiling data returned by xhprof.
39 * @var array $hieraData
41 protected $hieraData;
43 /**
44 * Per-function inclusive data.
45 * @var array $inclusive
47 protected $inclusive;
49 /**
50 * Per-function inclusive and exclusive data.
51 * @var array $complete
53 protected $complete;
55 /**
56 * Configuration data can contain:
57 * - flags: Optional flags to add additional information to the
58 * profiling data collected.
59 * (XHPROF_FLAGS_NO_BUILTINS, XHPROF_FLAGS_CPU,
60 * XHPROF_FLAGS_MEMORY)
61 * - exclude: Array of function names to exclude from profiling.
62 * - include: Array of function names to include in profiling.
63 * - sort: Key to sort per-function reports on.
65 * Note: When running under HHVM, xhprof will always behave as though the
66 * XHPROF_FLAGS_NO_BUILTINS flag has been used unless the
67 * Eval.JitEnableRenameFunction option is enabled for the HHVM process.
69 * @param array $config
71 public function __construct( array $config = array() ) {
72 $this->config = array_merge(
73 array(
74 'flags' => 0,
75 'exclude' => array(),
76 'include' => null,
77 'sort' => 'wt',
79 $config
82 xhprof_enable( $this->config['flags'], array(
83 'ignored_functions' => $this->config['exclude']
84 ) );
87 /**
88 * Stop collecting profiling data.
90 * Only the first invocation of this method will effect the internal
91 * object state. Subsequent calls will return the data collected by the
92 * initial call.
94 * @return array Collected profiling data (possibly cached)
96 public function stop() {
97 if ( $this->hieraData === null ) {
98 $this->hieraData = $this->pruneData( xhprof_disable() );
100 return $this->hieraData;
104 * Load raw data from a prior run for analysis.
105 * Stops any existing data collection and clears internal caches.
107 * Any 'include' filters configured for this Xhprof instance will be
108 * enforced on the data as it is loaded. 'exclude' filters will however
109 * not be enforced as they are an XHProf intrinsic behavior.
111 * @param array $data
112 * @see getRawData()
114 public function loadRawData( array $data ) {
115 $this->stop();
116 $this->inclusive = null;
117 $this->complete = null;
118 $this->hieraData = $this->pruneData( $data );
122 * Get raw data collected by xhprof.
124 * If data collection has not been stopped yet this method will halt
125 * collection to gather the profiling data.
127 * Each key in the returned array is an edge label for the call graph in
128 * the form "caller==>callee". There is once special case edge labled
129 * simply "main()" which represents the global scope entry point of the
130 * application.
132 * XHProf will collect different data depending on the flags that are used:
133 * - ct: Number of matching events seen.
134 * - wt: Inclusive elapsed wall time for this event in microseconds.
135 * - cpu: Inclusive elapsed cpu time for this event in microseconds.
136 * (XHPROF_FLAGS_CPU)
137 * - mu: Delta of memory usage from start to end of callee in bytes.
138 * (XHPROF_FLAGS_MEMORY)
139 * - pmu: Delta of peak memory usage from start to end of callee in
140 * bytes. (XHPROF_FLAGS_MEMORY)
141 * - alloc: Delta of amount memory requested from malloc() by the callee,
142 * in bytes. (XHPROF_FLAGS_MALLOC)
143 * - free: Delta of amount of memory passed to free() by the callee, in
144 * bytes. (XHPROF_FLAGS_MALLOC)
146 * @return array
147 * @see stop()
148 * @see getInclusiveMetrics()
149 * @see getCompleteMetrics()
151 public function getRawData() {
152 return $this->stop();
156 * Convert an xhprof data key into an array of ['parent', 'child']
157 * function names.
159 * The resulting array is left padded with nulls, so a key
160 * with no parent (eg 'main()') will return [null, 'function'].
162 * @return array
164 public static function splitKey( $key ) {
165 return array_pad( explode( '==>', $key, 2 ), -2, null );
169 * Remove data for functions that are not included in the 'include'
170 * configuration array.
172 * @param array $data Raw xhprof data
173 * @return array
175 protected function pruneData( $data ) {
176 if ( !$this->config['include'] ) {
177 return $data;
180 $want = array_fill_keys( $this->config['include'], true );
181 $want['main()'] = true;
183 $keep = array();
184 foreach ( $data as $key => $stats ) {
185 list( $parent, $child ) = self::splitKey( $key );
186 if ( isset( $want[$parent] ) || isset( $want[$child] ) ) {
187 $keep[$key] = $stats;
190 return $keep;
194 * Get the inclusive metrics for each function call. Inclusive metrics
195 * for given function include the metrics for all functions that were
196 * called from that function during the measurement period.
198 * If data collection has not been stopped yet this method will halt
199 * collection to gather the profiling data.
201 * See getRawData() for a description of the metric that are returned for
202 * each funcition call. The values for the wt, cpu, mu and pmu metrics are
203 * arrays with these values:
204 * - total: Cumulative value
205 * - min: Minimum value
206 * - mean: Mean (average) value
207 * - max: Maximum value
208 * - variance: Variance (spread) of the values
210 * @return array
211 * @see getRawData()
212 * @see getCompleteMetrics()
214 public function getInclusiveMetrics() {
215 if ( $this->inclusive === null ) {
216 // Make sure we have data to work with
217 $this->stop();
219 $main = $this->hieraData['main()'];
220 $hasCpu = isset( $main['cpu'] );
221 $hasMu = isset( $main['mu'] );
222 $hasAlloc = isset( $main['alloc'] );
224 $this->inclusive = array();
225 foreach ( $this->hieraData as $key => $stats ) {
226 list( $parent, $child ) = self::splitKey( $key );
227 if ( !isset( $this->inclusive[$child] ) ) {
228 $this->inclusive[$child] = array(
229 'ct' => 0,
230 'wt' => new RunningStat(),
232 if ( $hasCpu ) {
233 $this->inclusive[$child]['cpu'] = new RunningStat();
235 if ( $hasMu ) {
236 $this->inclusive[$child]['mu'] = new RunningStat();
237 $this->inclusive[$child]['pmu'] = new RunningStat();
239 if ( $hasAlloc ) {
240 $this->inclusive[$child]['alloc'] = new RunningStat();
241 $this->inclusive[$child]['free'] = new RunningStat();
245 $this->inclusive[$child]['ct'] += $stats['ct'];
246 foreach ( $stats as $stat => $value ) {
247 if ( $stat === 'ct' ) {
248 continue;
251 if ( !isset( $this->inclusive[$child][$stat] ) ) {
252 // Ignore unknown stats
253 continue;
256 for ( $i = 0; $i < $stats['ct']; $i++ ) {
257 $this->inclusive[$child][$stat]->push(
258 $value / $stats['ct']
264 // Convert RunningStat instances to static arrays and add
265 // percentage stats.
266 foreach ( $this->inclusive as $func => $stats ) {
267 foreach ( $stats as $name => $value ) {
268 if ( $value instanceof RunningStat ) {
269 $total = $value->m1 * $value->n;
270 $this->inclusive[$func][$name] = array(
271 'total' => $total,
272 'min' => $value->min,
273 'mean' => $value->m1,
274 'max' => $value->max,
275 'variance' => $value->m2,
276 'percent' => 100 * $total / $main[$name],
282 uasort( $this->inclusive, self::makeSortFunction(
283 $this->config['sort'], 'total'
284 ) );
286 return $this->inclusive;
290 * Get the inclusive and exclusive metrics for each function call.
292 * If data collection has not been stopped yet this method will halt
293 * collection to gather the profiling data.
295 * In addition to the normal data contained in the inclusive metrics, the
296 * metrics have an additional 'exclusive' measurement which is the total
297 * minus the totals of all child function calls.
299 * @return array
300 * @see getRawData()
301 * @see getInclusiveMetrics()
303 public function getCompleteMetrics() {
304 if ( $this->complete === null ) {
305 // Start with inclusive data
306 $this->complete = $this->getInclusiveMetrics();
308 foreach ( $this->complete as $func => $stats ) {
309 foreach ( $stats as $stat => $value ) {
310 if ( $stat === 'ct' ) {
311 continue;
313 // Initialize exclusive data with inclusive totals
314 $this->complete[$func][$stat]['exclusive'] = $value['total'];
316 // Add sapce for call tree information to be filled in later
317 $this->complete[$func]['calls'] = array();
318 $this->complete[$func]['subcalls'] = array();
321 foreach( $this->hieraData as $key => $stats ) {
322 list( $parent, $child ) = self::splitKey( $key );
323 if ( $parent !== null ) {
324 // Track call tree information
325 $this->complete[$child]['calls'][$parent] = $stats;
326 $this->complete[$parent]['subcalls'][$child] = $stats;
329 if ( isset( $this->complete[$parent] ) ) {
330 // Deduct child inclusive data from exclusive data
331 foreach ( $stats as $stat => $value ) {
332 if ( $stat === 'ct' ) {
333 continue;
336 if ( !isset( $this->complete[$parent][$stat] ) ) {
337 // Ignore unknown stats
338 continue;
341 $this->complete[$parent][$stat]['exclusive'] -= $value;
346 uasort( $this->complete, self::makeSortFunction(
347 $this->config['sort'], 'exclusive'
348 ) );
350 return $this->complete;
354 * Get a list of all callers of a given function.
356 * @param string $function Function name
357 * @return array
358 * @see getEdges()
360 public function getCallers( $function ) {
361 $edges = $this->getCompleteMetrics();
362 if ( isset( $edges[$function]['calls'] ) ) {
363 return array_keys( $edges[$function]['calls'] );
364 } else {
365 return array();
370 * Get a list of all callees from a given function.
372 * @param string $function Function name
373 * @return array
374 * @see getEdges()
376 public function getCallees( $function ) {
377 $edges = $this->getCompleteMetrics();
378 if ( isset( $edges[$function]['subcalls'] ) ) {
379 return array_keys( $edges[$function]['subcalls'] );
380 } else {
381 return array();
386 * Find the critical path for the given metric.
388 * @param string $metric Metric to find critical path for
389 * @return array
391 public function getCriticalPath( $metric = 'wt' ) {
392 $this->stop();
393 $func = 'main()';
394 $path = array(
395 $func => $this->hieraData[$func],
397 while ( $func ) {
398 $callees = $this->getCallees( $func );
399 $maxCallee = null;
400 $maxCall = null;
401 foreach ( $callees as $callee ) {
402 $call = "{$func}==>{$callee}";
403 if ( $maxCall === null ||
404 $this->hieraData[$call][$metric] >
405 $this->hieraData[$maxCall][$metric]
407 $maxCallee = $callee;
408 $maxCall = $call;
411 if ( $maxCall !== null ) {
412 $path[$maxCall] = $this->hieraData[$maxCall];
414 $func = $maxCallee;
416 return $path;
420 * Make a closure to use as a sort function. The resulting function will
421 * sort by descending numeric values (largest value first).
423 * @param string $key Data key to sort on
424 * @param string $sub Sub key to sort array values on
425 * @return Closure
427 public static function makeSortFunction( $key, $sub ) {
428 return function ( $a, $b ) use ( $key, $sub ) {
429 if ( isset( $a[$key] ) && isset( $b[$key] ) ) {
430 // Descending sort: larger values will be first in result.
431 // Assumes all values are numeric.
432 // Values for 'main()' will not have sub keys
433 $valA = is_array( $a[$key] ) ? $a[$key][$sub] : $a[$key];
434 $valB = is_array( $b[$key] ) ? $b[$key][$sub] : $b[$key];
435 return $valB - $valA;
436 } else {
437 // Sort datum with the key before those without
438 return isset( $a[$key] ) ? -1 : 1;