Debian Codegraph @

includes/profiler/SectionProfiler.php

raw symbols SCIP
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use Psr\Log\LoggerInterface;
23
24 /**
25 * Arbitrary section name based PHP profiling.
26 *
27 * This custom profiler can track code execution that doesn't cleanly map to a
28 * function call and thus can't be handled by ProfilerXhprof or ProfilerExcimer.
29 * For example, parser invocations or DB queries.
30 *
31 * @since 1.25
32 * @ingroup Profiler
33 */
34 class SectionProfiler {
35 /** @var array|null Map of (mem,real,cpu) */
36 protected $start;
37 /** @var array|null Map of (mem,real,cpu) */
38 protected $end;
39 /** @var array[] List of resolved profile calls with start/end data */
40 protected $stack = [];
41 /** @var array Queue of open profile calls with start data */
42 protected $workStack = [];
43 /** @var array[] Map of (function name => aggregate data array) */
44 protected $collated = [];
45 /** @var bool */
46 protected $collateDone = false;
47
48 /** @var array Cache of a standard broken collation entry */
49 protected $errorEntry;
50 /** @var LoggerInterface */
51 protected $logger;
52
53 /**
54 * @param array $params
55 */
56 public function __construct( array $params = [] ) {
57 $this->errorEntry = $this->getErrorEntry();
58 $this->logger = LoggerFactory::getInstance( 'profiler' );
59 }
60
61 /**
62 * @param string $section
63 */
64 public function scopedProfileIn( $section ): ?SectionProfileCallback {
65 $this->profileInInternal( $section );
66
67 return new SectionProfileCallback( $this, $section );
68 }
69
70 /**
71 * @param ?SectionProfileCallback &$section
72 */
73 public function scopedProfileOut( ?SectionProfileCallback &$section ) {
74 $section = null;
75 }
76
77 /**
78 * Get the aggregated inclusive profiling data for each method
79 *
80 * The percent time for each time is based on the current "total" time
81 * used is based on all methods so far. This method can therefore be
82 * called several times in between several profiling calls without the
83 * delays in usage of the profiler skewing the results. A "-total" entry
84 * is always included in the results.
85 *
86 * @return array[] List of method entries arrays, each having:
87 * - name : method name
88 * - calls : the number of invoking calls
89 * - real : real time elapsed (ms)
90 * - %real : percent real time
91 * - cpu : real time elapsed (ms)
92 * - %cpu : percent real time
93 * - memory : memory used (bytes)
94 * - %memory : percent memory used
95 * - min_real : min real time in a call (ms)
96 * - max_real : max real time in a call (ms)
97 */
98 public function getFunctionStats() {
99 $this->collateData();
100
101 if ( is_array( $this->start ) && is_array( $this->end ) ) {
102 $totalCpu = max( $this->end['cpu'] - $this->start['cpu'], 0 );
103 $totalReal = max( $this->end['real'] - $this->start['real'], 0 );
104 $totalMem = max( $this->end['memory'] - $this->start['memory'], 0 );
105 } else {
106 $totalCpu = 0;
107 $totalReal = 0;
108 $totalMem = 0;
109 }
110
111 $profile = [];
112 foreach ( $this->collated as $fname => $data ) {
113 $profile[] = [
114 'name' => $fname,
115 'calls' => $data['count'],
116 'real' => $data['real'] * 1000,
117 '%real' => $totalReal ? 100 * $data['real'] / $totalReal : 0,
118 'cpu' => $data['cpu'] * 1000,
119 '%cpu' => $totalCpu ? 100 * $data['cpu'] / $totalCpu : 0,
120 'memory' => $data['memory'],
121 '%memory' => $totalMem ? 100 * $data['memory'] / $totalMem : 0,
122 'min_real' => 1000 * $data['min_real'],
123 'max_real' => 1000 * $data['max_real']
124 ];
125 }
126
127 $profile[] = [
128 'name' => '-total',
129 'calls' => 1,
130 'real' => 1000 * $totalReal,
131 '%real' => 100,
132 'cpu' => 1000 * $totalCpu,
133 '%cpu' => 100,
134 'memory' => $totalMem,
135 '%memory' => 100,
136 'min_real' => 1000 * $totalReal,
137 'max_real' => 1000 * $totalReal
138 ];
139
140 return $profile;
141 }
142
143 /**
144 * Clear all of the profiling data for another run
145 */
146 public function reset() {
147 $this->start = null;
148 $this->end = null;
149 $this->stack = [];
150 $this->workStack = [];
151 $this->collated = [];
152 $this->collateDone = false;
153 }
154
155 /**
156 * @return array Initial collation entry
157 */
158 protected function getZeroEntry() {
159 return [
160 'cpu' => 0.0,
161 'real' => 0.0,
162 'memory' => 0,
163 'count' => 0,
164 'min_real' => 0.0,
165 'max_real' => 0.0
166 ];
167 }
168
169 /**
170 * @return array Initial collation entry for errors
171 */
172 protected function getErrorEntry() {
173 $entry = $this->getZeroEntry();
174 $entry['count'] = 1;
175 return $entry;
176 }
177
178 /**
179 * Update the collation entry for a given method name
180 *
181 * @param string $name
182 * @param float $elapsedCpu
183 * @param float $elapsedReal
184 * @param int $memChange
185 */
186 protected function updateEntry( $name, $elapsedCpu, $elapsedReal, $memChange ) {
187 $entry =& $this->collated[$name];
188 if ( !is_array( $entry ) ) {
189 $entry = $this->getZeroEntry();
190 $this->collated[$name] =& $entry;
191 }
192 $entry['cpu'] += $elapsedCpu;
193 $entry['real'] += $elapsedReal;
194 $entry['memory'] += $memChange > 0 ? $memChange : 0;
195 $entry['count']++;
196 $entry['min_real'] = min( $entry['min_real'], $elapsedReal );
197 $entry['max_real'] = max( $entry['max_real'], $elapsedReal );
198 }
199
200 /**
201 * This method should not be called outside SectionProfiler
202 *
203 * @param string $functionname
204 */
205 public function profileInInternal( $functionname ) {
206 // Once the data is collated for reports, any future calls
207 // should clear the collation cache so the next report will
208 // reflect them. This matters when trace mode is used.
209 $this->collateDone = false;
210
211 $cpu = $this->getTime( 'cpu' );
212 $real = $this->getTime( 'wall' );
213 $memory = memory_get_usage();
214
215 if ( $this->start === null ) {
216 $this->start = [ 'cpu' => $cpu, 'real' => $real, 'memory' => $memory ];
217 }
218
219 $this->workStack[] = [
220 $functionname,
221 count( $this->workStack ),
222 $real,
223 $cpu,
224 $memory
225 ];
226 }
227
228 /**
229 * This method should not be called outside SectionProfiler
230 *
231 * @param string $functionname
232 */
233 public function profileOutInternal( $functionname ) {
234 $item = array_pop( $this->workStack );
235 if ( $item === null ) {
236 $this->logger->error( "Profiling error: $functionname" );
237 return;
238 }
239 [ $ofname, /* $ocount */, $ortime, $octime, $omem ] = $item;
240
241 if ( $functionname === 'close' ) {
242 $message = "Profile section ended by close(): {$ofname}";
243 $this->logger->error( $message );
244 $this->collated[$message] = $this->errorEntry;
245 $functionname = $ofname;
246 } elseif ( $ofname !== $functionname ) {
247 $message = "Profiling error: in({$ofname}), out($functionname)";
248 $this->logger->error( $message );
249 $this->collated[$message] = $this->errorEntry;
250 }
251
252 $realTime = $this->getTime( 'wall' );
253 $cpuTime = $this->getTime( 'cpu' );
254 $memUsage = memory_get_usage();
255
256 $elapsedcpu = $cpuTime - $octime;
257 $elapsedreal = $realTime - $ortime;
258 $memchange = $memUsage - $omem;
259 $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
260
261 $this->end = [
262 'cpu' => $cpuTime,
263 'real' => $realTime,
264 'memory' => $memUsage
265 ];
266 }
267
268 /**
269 * Populate collated data
270 */
271 protected function collateData() {
272 if ( $this->collateDone ) {
273 return;
274 }
275 $this->collateDone = true;
276 // Close opened profiling sections
277 while ( count( $this->workStack ) ) {
278 $this->profileOutInternal( 'close' );
279 }
280 }
281
282 /**
283 * Get the initial time of the request, based on getrusage()
284 *
285 * @param string|bool $metric Metric to use, with the following possibilities:
286 * - user: User CPU time (without system calls)
287 * - cpu: Total CPU time (user and system calls)
288 * - wall (or any other string): elapsed time
289 * - false (default): will fall back to default metric
290 * @return float
291 */
292 protected function getTime( $metric = 'wall' ) {
293 if ( $metric === 'cpu' || $metric === 'user' ) {
294 $ru = getrusage( 0 /* RUSAGE_SELF */ );
295 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
296 if ( $metric === 'cpu' ) {
297 # This is the time of system calls, added to the user time
298 # it gives the total CPU time
299 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
300 }
301 return $time;
302 } else {
303 return microtime( true );
304 }
305 }
306 }