* New message: talkpagelinktext
[lhc/web/wiklou.git] / includes / Profiler.php
1 <?php
2 /**
3 * This file is only included if profiling is enabled
4 */
5
6 $wgProfiling = true;
7
8 /**
9 * @param $functioname name of the function we will profile
10 */
11 function wfProfileIn($functionname) {
12 global $wgProfiler;
13 $wgProfiler->profileIn($functionname);
14 }
15
16 /**
17 * @param $functioname name of the function we have profiled
18 */
19 function wfProfileOut($functionname = 'missing') {
20 global $wgProfiler;
21 $wgProfiler->profileOut($functionname);
22 }
23
24 function wfGetProfilingOutput($start, $elapsed) {
25 global $wgProfiler;
26 return $wgProfiler->getOutput($start, $elapsed);
27 }
28
29 function wfProfileClose() {
30 global $wgProfiler;
31 $wgProfiler->close();
32 }
33
34 if (!function_exists('memory_get_usage')) {
35 # Old PHP or --enable-memory-limit not compiled in
36 function memory_get_usage() {
37 return 0;
38 }
39 }
40
41 /**
42 * @todo document
43 */
44 class Profiler {
45 var $mStack = array (), $mWorkStack = array (), $mCollated = array ();
46 var $mCalls = array (), $mTotals = array ();
47
48 function __construct() {
49 // Push an entry for the pre-profile setup time onto the stack
50 global $wgRequestTime;
51 if ( !empty( $wgRequestTime ) ) {
52 $this->mWorkStack[] = array( '-total', 0, $wgRequestTime, 0 );
53 $this->mStack[] = array( '-setup', 1, $wgRequestTime, 0, microtime(true), 0 );
54 } else {
55 $this->profileIn( '-total' );
56 }
57 }
58
59 function profileIn($functionname) {
60 global $wgDebugFunctionEntry;
61 if ($wgDebugFunctionEntry && function_exists('wfDebug')) {
62 wfDebug(str_repeat(' ', count($this->mWorkStack)).'Entering '.$functionname."\n");
63 }
64 $this->mWorkStack[] = array($functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage());
65 }
66
67 function profileOut($functionname) {
68 $memory = memory_get_usage();
69 $time = $this->getTime();
70
71 global $wgDebugFunctionEntry;
72
73 if ($wgDebugFunctionEntry && function_exists('wfDebug')) {
74 wfDebug(str_repeat(' ', count($this->mWorkStack) - 1).'Exiting '.$functionname."\n");
75 }
76
77 $bit = array_pop($this->mWorkStack);
78
79 if (!$bit) {
80 wfDebug("Profiling error, !\$bit: $functionname\n");
81 } else {
82 //if ($wgDebugProfiling) {
83 if ($functionname == 'close') {
84 $message = "Profile section ended by close(): {$bit[0]}";
85 wfDebug( "$message\n" );
86 $this->mStack[] = array( $message, 0, '0 0', 0, '0 0', 0 );
87 }
88 elseif ($bit[0] != $functionname) {
89 $message = "Profiling error: in({$bit[0]}), out($functionname)";
90 wfDebug( "$message\n" );
91 $this->mStack[] = array( $message, 0, '0 0', 0, '0 0', 0 );
92 }
93 //}
94 $bit[] = $time;
95 $bit[] = $memory;
96 $this->mStack[] = $bit;
97 }
98 }
99
100 function close() {
101 while (count($this->mWorkStack)) {
102 $this->profileOut('close');
103 }
104 }
105
106 function getOutput() {
107 global $wgDebugFunctionEntry;
108 $wgDebugFunctionEntry = false;
109
110 if (!count($this->mStack) && !count($this->mCollated)) {
111 return "No profiling output\n";
112 }
113 $this->close();
114
115 global $wgProfileCallTree;
116 if ($wgProfileCallTree) {
117 return $this->getCallTree();
118 } else {
119 return $this->getFunctionReport();
120 }
121 }
122
123 function getCallTree($start = 0) {
124 return implode('', array_map(array (& $this, 'getCallTreeLine'), $this->remapCallTree($this->mStack)));
125 }
126
127 function remapCallTree($stack) {
128 if (count($stack) < 2) {
129 return $stack;
130 }
131 $outputs = array ();
132 for ($max = count($stack) - 1; $max > 0;) {
133 /* Find all items under this entry */
134 $level = $stack[$max][1];
135 $working = array ();
136 for ($i = $max -1; $i >= 0; $i --) {
137 if ($stack[$i][1] > $level) {
138 $working[] = $stack[$i];
139 } else {
140 break;
141 }
142 }
143 $working = $this->remapCallTree(array_reverse($working));
144 $output = array ();
145 foreach ($working as $item) {
146 array_push($output, $item);
147 }
148 array_unshift($output, $stack[$max]);
149 $max = $i;
150
151 array_unshift($outputs, $output);
152 }
153 $final = array ();
154 foreach ($outputs as $output) {
155 foreach ($output as $item) {
156 $final[] = $item;
157 }
158 }
159 return $final;
160 }
161
162 function getCallTreeLine($entry) {
163 list ($fname, $level, $start, /* $x */, $end) = $entry;
164 $delta = $end - $start;
165 $space = str_repeat(' ', $level);
166
167 # The ugly double sprintf is to work around a PHP bug,
168 # which has been fixed in recent releases.
169 return sprintf( "%10s %s %s\n",
170 trim( sprintf( "%7.3f", $delta * 1000.0 ) ),
171 $space, $fname );
172 }
173
174 function getTime() {
175 return microtime(true);
176 #return $this->getUserTime();
177 }
178
179 function getUserTime() {
180 $ru = getrusage();
181 return $ru['ru_utime.tv_sec'].' '.$ru['ru_utime.tv_usec'] / 1e6;
182 }
183
184 function getFunctionReport() {
185 $width = 140;
186 $nameWidth = $width - 65;
187 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
188 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
189 $prof = "\nProfiling data\n";
190 $prof .= sprintf($titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem');
191 $this->mCollated = array ();
192 $this->mCalls = array ();
193 $this->mMemory = array ();
194
195 # Estimate profiling overhead
196 $profileCount = count($this->mStack);
197 wfProfileIn('-overhead-total');
198 for ($i = 0; $i < $profileCount; $i ++) {
199 wfProfileIn('-overhead-internal');
200 wfProfileOut('-overhead-internal');
201 }
202 wfProfileOut('-overhead-total');
203
204 # First, subtract the overhead!
205 foreach ($this->mStack as $entry) {
206 $fname = $entry[0];
207 $start = $entry[2];
208 $end = $entry[4];
209 $elapsed = $end - $start;
210 $memory = $entry[5] - $entry[3];
211
212 if ($fname == '-overhead-total') {
213 $overheadTotal[] = $elapsed;
214 $overheadMemory[] = $memory;
215 }
216 elseif ($fname == '-overhead-internal') {
217 $overheadInternal[] = $elapsed;
218 }
219 }
220 $overheadTotal = array_sum($overheadTotal) / count($overheadInternal);
221 $overheadMemory = array_sum($overheadMemory) / count($overheadInternal);
222 $overheadInternal = array_sum($overheadInternal) / count($overheadInternal);
223
224 # Collate
225 foreach ($this->mStack as $index => $entry) {
226 $fname = $entry[0];
227 $start = $entry[2];
228 $end = $entry[4];
229 $elapsed = $end - $start;
230
231 $memory = $entry[5] - $entry[3];
232 $subcalls = $this->calltreeCount($this->mStack, $index);
233
234 if (!preg_match('/^-overhead/', $fname)) {
235 # Adjust for profiling overhead (except special values with elapsed=0
236 if ( $elapsed ) {
237 $elapsed -= $overheadInternal;
238 $elapsed -= ($subcalls * $overheadTotal);
239 $memory -= ($subcalls * $overheadMemory);
240 }
241 }
242
243 if (!array_key_exists($fname, $this->mCollated)) {
244 $this->mCollated[$fname] = 0;
245 $this->mCalls[$fname] = 0;
246 $this->mMemory[$fname] = 0;
247 $this->mMin[$fname] = 1 << 24;
248 $this->mMax[$fname] = 0;
249 $this->mOverhead[$fname] = 0;
250 }
251
252 $this->mCollated[$fname] += $elapsed;
253 $this->mCalls[$fname]++;
254 $this->mMemory[$fname] += $memory;
255 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
256 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
257 $this->mOverhead[$fname] += $subcalls;
258 }
259
260 $total = @ $this->mCollated['-total'];
261 $this->mCalls['-overhead-total'] = $profileCount;
262
263 # Output
264 arsort($this->mCollated, SORT_NUMERIC);
265 foreach ($this->mCollated as $fname => $elapsed) {
266 $calls = $this->mCalls[$fname];
267 $percent = $total ? 100. * $elapsed / $total : 0;
268 $memory = $this->mMemory[$fname];
269 $prof .= sprintf($format, substr($fname, 0, $nameWidth), $calls, (float) ($elapsed * 1000), (float) ($elapsed * 1000) / $calls, $percent, $memory, ($this->mMin[$fname] * 1000.0), ($this->mMax[$fname] * 1000.0), $this->mOverhead[$fname]);
270
271 global $wgProfileToDatabase;
272 if ($wgProfileToDatabase) {
273 Profiler :: logToDB($fname, (float) ($elapsed * 1000), $calls);
274 }
275 }
276 $prof .= "\nTotal: $total\n\n";
277
278 return $prof;
279 }
280
281 /**
282 * Counts the number of profiled function calls sitting under
283 * the given point in the call graph. Not the most efficient algo.
284 *
285 * @param $stack Array:
286 * @param $start Integer:
287 * @return Integer
288 * @private
289 */
290 function calltreeCount($stack, $start) {
291 $level = $stack[$start][1];
292 $count = 0;
293 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
294 $count ++;
295 }
296 return $count;
297 }
298
299 /**
300 * @static
301 */
302 function logToDB($name, $timeSum, $eventCount) {
303 # Warning: $wguname is a live patch, it should be moved to Setup.php
304 global $wguname, $wgProfilePerHost;
305
306 $fname = 'Profiler::logToDB';
307 $dbw = wfGetDB(DB_MASTER);
308 if (!is_object($dbw))
309 return false;
310 $errorState = $dbw->ignoreErrors( true );
311 $profiling = $dbw->tableName('profiling');
312
313 $name = substr($name, 0, 255);
314 $encname = $dbw->strencode($name);
315
316 if ($wgProfilePerHost) {
317 $pfhost = $wguname['nodename'];
318 } else {
319 $pfhost = '';
320 }
321
322 $sql = "UPDATE $profiling "."SET pf_count=pf_count+{$eventCount}, "."pf_time=pf_time + {$timeSum} ".
323 "WHERE pf_name='{$encname}' AND pf_server='{$pfhost}'";
324 $dbw->query($sql);
325
326 $rc = $dbw->affectedRows();
327 if ($rc == 0) {
328 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount,
329 'pf_time' => $timeSum, 'pf_server' => $pfhost ), $fname, array ('IGNORE'));
330 }
331 // When we upgrade to mysql 4.1, the insert+update
332 // can be merged into just a insert with this construct added:
333 // "ON DUPLICATE KEY UPDATE ".
334 // "pf_count=pf_count + VALUES(pf_count), ".
335 // "pf_time=pf_time + VALUES(pf_time)";
336 $dbw->ignoreErrors( $errorState );
337 }
338
339 /**
340 * Get the function name of the current profiling section
341 */
342 function getCurrentSection() {
343 $elt = end($this->mWorkStack);
344 return $elt[0];
345 }
346
347 static function getCaller( $level ) {
348 $backtrace = wfDebugBacktrace();
349 if ( isset( $backtrace[$level] ) ) {
350 if ( isset( $backtrace[$level]['class'] ) ) {
351 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
352 } else {
353 $caller = $backtrace[$level]['function'];
354 }
355 } else {
356 $caller = 'unknown';
357 }
358 return $caller;
359 }
360
361 }
362
363 ?>