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