* Added a test for a link with multiple pipes
[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 $this->mProfileStack = array();
51 $this->mWorkStack = array();
52 $this->mCollated = array();
53 }
54 */
55
56 function profileIn($functionname) {
57 global $wgDebugFunctionEntry;
58 if ($wgDebugFunctionEntry && function_exists('wfDebug')) {
59 wfDebug(str_repeat(' ', count($this->mWorkStack)).'Entering '.$functionname."\n");
60 }
61 $this->mWorkStack[] = array ($functionname, count($this->mWorkStack), microtime(), memory_get_usage());
62 }
63
64 function profileOut($functionname) {
65 $memory = memory_get_usage();
66 $time = microtime();
67 global $wgDebugProfiling, $wgDebugFunctionEntry;
68
69 if ($wgDebugFunctionEntry && function_exists('wfDebug')) {
70 wfDebug(str_repeat(' ', count($this->mWorkStack)).'Exiting '.$functionname."\n");
71 }
72
73 $bit = array_pop($this->mWorkStack);
74
75 if (!$bit) {
76 wfDebug("Profiling error, !\$bit: $functionname\n");
77 } else {
78 if ($wgDebugProfiling) {
79 if ($functionname == 'close') {
80 wfDebug("Profile section ended by close(): {$bit[0]}\n");
81 }
82 elseif ($bit[0] != $functionname) {
83 wfDebug("Profiling error: in({$bit[0]}), out($functionname)\n");
84 }
85 }
86 $bit[] = $time;
87 $bit[] = $memory;
88 $this->mStack[] = $bit;
89 }
90 }
91
92 function close() {
93 while (count($this->mWorkStack)) {
94 $this->profileOut('close');
95 }
96 }
97
98 function getOutput() {
99 global $wgDebugFunctionEntry;
100 $wgDebugFunctionEntry = false;
101
102 if (!count($this->mStack)) {
103 return "No profiling output\n";
104 }
105 $this->close();
106
107 global $wgProfileCallTree;
108 if ($wgProfileCallTree) {
109 return $this->getCallTree();
110 } else {
111 return $this->getFunctionReport();
112 }
113 }
114
115 function getCallTree($start = 0) {
116 return implode('', array_map(array (& $this, 'getCallTreeLine'), $this->remapCallTree($this->mStack)));
117 }
118
119 function remapCallTree($stack) {
120 if (count($stack) < 2) {
121 return $stack;
122 }
123 $outputs = array ();
124 for ($max = count($stack) - 1; $max > 0;) {
125 /* Find all items under this entry */
126 $level = $stack[$max][1];
127 $working = array ();
128 for ($i = $max -1; $i >= 0; $i --) {
129 if ($stack[$i][1] > $level) {
130 $working[] = $stack[$i];
131 } else {
132 break;
133 }
134 }
135 $working = $this->remapCallTree(array_reverse($working));
136 $output = array ();
137 foreach ($working as $item) {
138 array_push($output, $item);
139 }
140 array_unshift($output, $stack[$max]);
141 $max = $i;
142
143 array_unshift($outputs, $output);
144 }
145 $final = array ();
146 foreach ($outputs as $output) {
147 foreach ($output as $item) {
148 $final[] = $item;
149 }
150 }
151 return $final;
152 }
153
154 function getCallTreeLine($entry) {
155 list ($fname, $level, $start, $x, $end) = $entry;
156 $delta = $this->microDelta($start, $end);
157 $space = str_repeat(' ', $level);
158
159 # The ugly double sprintf is to work around a PHP bug,
160 # which has been fixed in recent releases.
161 return sprintf("%10s %s %s\n", trim(sprintf("%7.3f", $delta * 1000.0)), $space, $fname);
162 }
163
164 function micro2Float($micro) {
165 list ($whole, $fractional) = explode(' ', $micro);
166 return (float) $whole + (float) $fractional;
167 }
168
169 function microDelta($start, $end) {
170 return $this->micro2Float($end) - $this->micro2Float($start);
171 }
172
173 function getFunctionReport() {
174 $width = 125;
175 $format = "%-". ($width -34)."s %6d %6.3f %6.3f %7.3f%% %6d (%6.3f-%6.3f) [%d]\n";
176 $titleFormat = "%-". ($width -34)."s %9s %9s %9s %9s %6s\n";
177 $prof = "\nProfiling data\n";
178 $prof .= sprintf($titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem');
179 $this->mCollated = array ();
180 $this->mCalls = array ();
181 $this->mMemory = array ();
182
183 # Estimate profiling overhead
184 $profileCount = count($this->mStack);
185 wfProfileIn('-overhead-total');
186 for ($i = 0; $i < $profileCount; $i ++) {
187 wfProfileIn('-overhead-internal');
188 wfProfileOut('-overhead-internal');
189 }
190 wfProfileOut('-overhead-total');
191
192 # First, subtract the overhead!
193 foreach ($this->mStack as $entry) {
194 $fname = $entry[0];
195 $thislevel = $entry[1];
196 $start = explode(' ', $entry[2]);
197 $start = (float) $start[0] + (float) $start[1];
198 $end = explode(' ', $entry[4]);
199 $end = (float) $end[0] + (float) $end[1];
200 $elapsed = $end - $start;
201 $memory = $entry[5] - $entry[3];
202
203 if ($fname == '-overhead-total') {
204 $overheadTotal[] = $elapsed;
205 $overheadMemory[] = $memory;
206 }
207 elseif ($fname == '-overhead-internal') {
208 $overheadInternal[] = $elapsed;
209 }
210 }
211 $overheadTotal = array_sum($overheadTotal) / count($overheadInternal);
212 $overheadMemory = array_sum($overheadMemory) / count($overheadInternal);
213 $overheadInternal = array_sum($overheadInternal) / count($overheadInternal);
214
215 # Collate
216 foreach ($this->mStack as $index => $entry) {
217 $fname = $entry[0];
218 $thislevel = $entry[1];
219 $start = explode(' ', $entry[2]);
220 $start = (float) $start[0] + (float) $start[1];
221 $end = explode(' ', $entry[4]);
222 $end = (float) $end[0] + (float) $end[1];
223 $elapsed = $end - $start;
224
225 $memory = $entry[5] - $entry[3];
226 $subcalls = $this->calltreeCount($this->mStack, $index);
227
228 if (!preg_match('/^-overhead/', $fname)) {
229 # Adjust for profiling overhead
230 $elapsed -= $overheadInternal;
231 $elapsed -= ($subcalls * $overheadTotal);
232 $memory -= ($subcalls * $overheadMemory);
233 }
234
235 if (!array_key_exists($fname, $this->mCollated)) {
236 $this->mCollated[$fname] = 0;
237 $this->mCalls[$fname] = 0;
238 $this->mMemory[$fname] = 0;
239 $this->mMin[$fname] = 1 << 24;
240 $this->mMax[$fname] = 0;
241 $this->mOverhead[$fname] = 0;
242 }
243
244 $this->mCollated[$fname] += $elapsed;
245 $this->mCalls[$fname]++;
246 $this->mMemory[$fname] += $memory;
247 $this->mMin[$fname] = min($this->mMin[$fname], $elapsed);
248 $this->mMax[$fname] = max($this->mMax[$fname], $elapsed);
249 $this->mOverhead[$fname] += $subcalls;
250 }
251
252 $total = @ $this->mCollated['-total'];
253 $this->mCalls['-overhead-total'] = $profileCount;
254
255 # Output
256 asort($this->mCollated, SORT_NUMERIC);
257 foreach ($this->mCollated as $fname => $elapsed) {
258 $calls = $this->mCalls[$fname];
259 $percent = $total ? 100. * $elapsed / $total : 0;
260 $memory = $this->mMemory[$fname];
261 $prof .= sprintf($format, $fname, $calls, (float) ($elapsed * 1000), (float) ($elapsed * 1000) / $calls, $percent, $memory, ($this->mMin[$fname] * 1000.0), ($this->mMax[$fname] * 1000.0), $this->mOverhead[$fname]);
262
263 global $wgProfileToDatabase;
264 if ($wgProfileToDatabase) {
265 Profiler :: logToDB($fname, (float) ($elapsed * 1000), $calls);
266 }
267 }
268 $prof .= "\nTotal: $total\n\n";
269
270 return $prof;
271 }
272
273 /**
274 * Counts the number of profiled function calls sitting under
275 * the given point in the call graph. Not the most efficient algo.
276 *
277 * @param array $stack
278 * @param int $start
279 * @return int
280 * @access private
281 */
282 function calltreeCount(& $stack, $start) {
283 $level = $stack[$start][1];
284 $count = 0;
285 for ($i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i --) {
286 $count ++;
287 }
288 return $count;
289 }
290
291 /**
292 * @static
293 */
294 function logToDB($name, $timeSum, $eventCount) {
295 $fname = 'Profiler::logToDB';
296 $dbw = & wfGetDB(DB_MASTER);
297 $profiling = $dbw->tableName('profiling');
298
299 $name = substr($name, 0, 255);
300 $encname = $dbw->strencode($name);
301 $sql = "UPDATE $profiling "."SET pf_count=pf_count+{$eventCount}, "."pf_time=pf_time + {$timeSum} "."WHERE pf_name='{$encname}'";
302 $dbw->query($sql);
303
304 $rc = $dbw->affectedRows();
305 if ($rc == 0) {
306 $dbw->insert('profiling', array ('pf_name' => $name, 'pf_count' => $eventCount, 'pf_time' => $timeSum), $fname, array ('IGNORE'));
307 }
308 // When we upgrade to mysql 4.1, the insert+update
309 // can be merged into just a insert with this construct added:
310 // "ON DUPLICATE KEY UPDATE ".
311 // "pf_count=pf_count + VALUES(pf_count), ".
312 // "pf_time=pf_time + VALUES(pf_time)";
313 }
314
315 }
316
317 $wgProfiler = new Profiler();
318 $wgProfiler->profileIn('-total');
319 ?>