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