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