summaryrefslogtreecommitdiff
path: root/includes/profiler/ProfilerXhprof.php
blob: 5f7fc0028a0bd4e9bb51b87015c9b7b4f073a995 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * Profiler wrapper for XHProf extension.
 *
 * @code
 * $wgProfiler['class'] = 'ProfilerXhprof';
 * $wgProfiler['flags'] = XHPROF_FLAGS_NO_BUILTINS;
 * $wgProfiler['output'] = 'text';
 * $wgProfiler['visible'] = true;
 * @endcode
 *
 * @code
 * $wgProfiler['class'] = 'ProfilerXhprof';
 * $wgProfiler['flags'] = XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_NO_BUILTINS;
 * $wgProfiler['output'] = 'udp';
 * @endcode
 *
 * ProfilerXhprof profiles all functions using the XHProf PHP extenstion.
 * For PHP5 users, this extension can be installed via PECL or your operating
 * system's package manager. XHProf support is built into HHVM.
 *
 * To restrict the functions for which profiling data is collected, you can
 * use either a whitelist ($wgProfiler['include']) or a blacklist
 * ($wgProfiler['exclude']) containing an array of function names.
 * Shell-style patterns are also accepted.
 *
 * @author Bryan Davis <bd808@wikimedia.org>
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
 * @ingroup Profiler
 * @see Xhprof
 * @see https://php.net/xhprof
 * @see https://github.com/facebook/hhvm/blob/master/hphp/doc/profiling.md
 */
class ProfilerXhprof extends Profiler {
	/**
	 * @var Xhprof $xhprof
	 */
	protected $xhprof;

	/**
	 * Profiler for explicit, arbitrary, frame labels
	 * @var SectionProfiler
	 */
	protected $sprofiler;

	/**
	 * @param array $params
	 * @see Xhprof::__construct()
	 */
	public function __construct( array $params = array() ) {
		parent::__construct( $params );
		$this->xhprof = new Xhprof( $params );
		$this->sprofiler = new SectionProfiler();
	}

	public function scopedProfileIn( $section ) {
		$key = 'section.' . ltrim( $section, '.' );
		return $this->sprofiler->scopedProfileIn( $key );
	}

	/**
	 * No-op for xhprof profiling.
	 */
	public function close() {
	}

	/**
	 * Check if a function or section should be excluded from the output.
	 *
	 * @param string $name Function or section name.
	 * @return bool
	 */
	private function shouldExclude( $name ) {
		if ( $name === '-total' ) {
			return true;
		}
		if ( !empty( $this->params['include'] ) ) {
			foreach ( $this->params['include'] as $pattern ) {
				if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
					return false;
				}
			}
			return true;
		}
		if ( !empty( $this->params['exclude'] ) ) {
			foreach ( $this->params['exclude'] as $pattern ) {
				if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
					return true;
				}
			}
		}
		return false;
	}

	public function getFunctionStats() {
		$metrics = $this->xhprof->getCompleteMetrics();
		$profile = array();

		$main = null; // units in ms
		foreach ( $metrics as $fname => $stats ) {
			if ( $this->shouldExclude( $fname ) ) {
				continue;
			}
			// Convert elapsed times from μs to ms to match interface
			$entry = array(
				'name' => $fname,
				'calls' => $stats['ct'],
				'real' => $stats['wt']['total'] / 1000,
				'%real' => $stats['wt']['percent'],
				'cpu' => isset( $stats['cpu'] ) ? $stats['cpu']['total'] / 1000 : 0,
				'%cpu' => isset( $stats['cpu'] ) ? $stats['cpu']['percent'] : 0,
				'memory' => isset( $stats['mu'] ) ? $stats['mu']['total'] : 0,
				'%memory' => isset( $stats['mu'] ) ? $stats['mu']['percent'] : 0,
				'min_real' => $stats['wt']['min'] / 1000,
				'max_real' => $stats['wt']['max'] / 1000
			);
			$profile[] = $entry;
			if ( $fname === 'main()' ) {
				$main = $entry;
			}
		}

		// Merge in all of the custom profile sections
		foreach ( $this->sprofiler->getFunctionStats() as $stats ) {
			if ( $this->shouldExclude( $stats['name'] ) ) {
				continue;
			}

			// @note: getFunctionStats() values already in ms
			$stats['%real'] = $main['real'] ? $stats['real'] / $main['real'] * 100 : 0;
			$stats['%cpu'] = $main['cpu'] ? $stats['cpu'] / $main['cpu'] * 100 : 0;
			$stats['%memory'] = $main['memory'] ? $stats['memory'] / $main['memory'] * 100 : 0;
			$profile[] = $stats; // assume no section names collide with $metrics
		}

		return $profile;
	}

	/**
	 * Returns a profiling output to be stored in debug file
	 *
	 * @return string
	 */
	public function getOutput() {
		return $this->getFunctionReport();
	}

	/**
	 * Get a report of profiled functions sorted by inclusive wall clock time
	 * in descending order.
	 *
	 * Each line of the report includes this data:
	 * - Function name
	 * - Number of times function was called
	 * - Total wall clock time spent in function in microseconds
	 * - Minimum wall clock time spent in function in microseconds
	 * - Average wall clock time spent in function in microseconds
	 * - Maximum wall clock time spent in function in microseconds
	 * - Percentage of total wall clock time spent in function
	 * - Total delta of memory usage from start to end of function in bytes
	 *
	 * @return string
	 */
	protected function getFunctionReport() {
		$data = $this->getFunctionStats();
		usort( $data, function( $a, $b ) {
			if ( $a['real'] === $b['real'] ) {
				return 0;
			}
			return ( $a['real'] > $b['real'] ) ? -1 : 1; // descending
		} );

		$width = 140;
		$nameWidth = $width - 65;
		$format = "%-{$nameWidth}s %6d %9d %9d %9d %9d %7.3f%% %9d";
		$out = array();
		$out[] = sprintf( "%-{$nameWidth}s %6s %9s %9s %9s %9s %7s %9s",
			'Name', 'Calls', 'Total', 'Min', 'Each', 'Max', '%', 'Mem'
		);
		foreach ( $data as $stats ) {
			$out[] = sprintf( $format,
				$stats['name'],
				$stats['calls'],
				$stats['real'] * 1000,
				$stats['min_real'] * 1000,
				$stats['real'] / $stats['calls'] * 1000,
				$stats['max_real'] * 1000,
				$stats['%real'],
				$stats['memory']
			);
		}
		return implode( "\n", $out );
	}

	/**
	 * Retrieve raw data from xhprof
	 * @return array
	 */
	public function getRawData() {
		return $this->xhprof->getRawData();
	}
}