Usage.php 6.33 KB
Newer Older
1 2
<?php
/*
3
	Question2Answer by Gideon Greenspan and contributors
4 5
	http://www.question2answer.org/

Scott committed
6
	File: qa-include/Q2A/Util/Usage.php
7
	Description: Debugging stuff, currently used for tracking resource usage
8 9 10 11 12 13 14 15 16 17 18 19 20


	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
21 22 23 24
*/

class Q2A_Util_Usage
{
25 26 27 28 29
	private $stages;
	private $startUsage;
	private $prevUsage;
	private $databaseUsage;
	private $databaseQueryLog;
30 31

	/**
32
	 * Initialize the counts of resource usage.
33 34 35
	 */
	public function __construct()
	{
36 37 38
		$this->stages = array();
		$this->databaseUsage = array('queries'=>0, 'clock'=>0);
		$this->databaseQueryLog = '';
39

40
		$this->prevUsage = $this->startUsage = $this->getCurrent();
41 42 43
	}

	/**
44
	 * Return an array representing the resource usage as of now.
45 46 47 48 49
	 */
	public function getCurrent()
	{
		$usage = array(
			'files' => count(get_included_files()),
50
			'queries' => $this->databaseUsage['queries'],
51 52
			'ram' => function_exists('memory_get_usage') ? memory_get_usage() : 0,
			'clock' => array_sum(explode(' ', microtime())),
53
			'mysql' => $this->databaseUsage['clock'],
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
		);

		if (function_exists('getrusage')) {
			$rusage = getrusage();
			$usage['cpu'] = $rusage["ru_utime.tv_sec"] + $rusage["ru_stime.tv_sec"]
				+ ($rusage["ru_utime.tv_usec"] + $rusage["ru_stime.tv_usec"]) / 1000000;
		}
		else
			$usage['cpu'] = 0;

		$usage['other'] = $usage['clock'] - $usage['cpu'] - $usage['mysql'];

		return $usage;
	}

	/**
70
	 * Mark the beginning of a new stage of script execution and store usages accordingly.
71 72 73 74
	 */
	public function mark($stage)
	{
		$usage = $this->getCurrent();
75 76 77 78 79
		$this->stages[$stage] = $this->delta($this->prevUsage, $usage);
		$this->prevUsage = $usage;
	}

	/**
80
	 * Logs query and updates database usage stats.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
	 */
	public function logDatabaseQuery($query, $usedtime, $gotrows, $gotcolumns)
	{
		$this->databaseUsage['clock'] += $usedtime;

		if (strlen($this->databaseQueryLog) < 1048576) { // don't keep track of big tests
			$rowcolstring = '';
			if (is_numeric($gotrows))
				$rowcolstring .= ' - ' . $gotrows . ($gotrows == 1 ? ' row' : ' rows');
			if (is_numeric($gotcolumns))
				$rowcolstring .= ' - ' . $gotcolumns . ($gotcolumns == 1 ? ' column' : ' columns');

			$this->databaseQueryLog .= $query . "\n\n" . sprintf('%.2f ms', $usedtime*1000) . $rowcolstring . "\n\n";
		}

		$this->databaseUsage['queries']++;
97 98 99
	}

	/**
100
	 * Output an (ugly) block of HTML detailing all resource usage and database queries.
101 102 103
	 */
	public function output()
	{
104
		$totaldelta = $this->delta($this->startUsage, $this->getCurrent());
105 106
?>
		<style>
107 108
		.debug-table { border-collapse: collapse; width: auto; margin: 20px auto; }
		.debug-table th, .debug-table td { border: 1px solid #aaa; background-color: #ddd; padding: 5px 10px; }
109 110 111
		.debug-table td { text-align: right; }
		.debug-table th:empty { border: none; background-color: initial; }
		.debug-table .row-heading { font-weight: bold; }
112

113
		.debug-table tr:last-child td { background-color: #ccc; border-top-width: 3px; }
114 115

		textarea.debug-output { box-sizing: border-box; width: 100%; font: 12px monospace; color: #000; }
116

117 118 119 120 121
		.extra-info { border-collapse: collapse; box-sizing: border-box; width: 100%; }
		.extra-info td.debug-cell-files { width: 30%; padding: 10px 5px 10px 10px; }
		.extra-info td.debug-cell-queries { width: 70%; padding: 10px 10px 10px 5px; }
		.extra-info tr { background-color: #ccc; }
		.extra-info textarea { margin: 0; }
122 123 124
		</style>

		<table class="debug-table">
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
			<thead>
				<tr>
					<th></th>
					<th colspan="2">Total</th>
					<th colspan="3">PHP</th>
					<th colspan="3">MySQL</th>
					<th colspan="2">Other</th>
					<th colspan="2">RAM</th>
				</tr>
				<tr>
					<th></th>
					<th>Time (ms)</th>
					<th>%</th>
					<th>Time (ms)</th>
					<th>%</th>
					<th>File count</th>
					<th>Time (ms)</th>
					<th>%</th>
					<th>Query count</th>
					<th>Time (ms)</th>
					<th>%</th>
					<th>Amount</th>
					<th>%</th>
				</tr>
			</thead>
		<tbody>

			<?php
				$stages = $this->stages;
				$stages['total'] = $totaldelta;

				foreach ($stages as $stage => $stagedelta):
			?>
					<tr>
						<td class="row-heading"><?php echo ucfirst($stage); ?></td>
						<td><?php echo sprintf('%.1f', $stagedelta['clock'] * 1000); ?></td>
						<td><?php echo sprintf('%d%%', $stagedelta['clock'] * 100 / $totaldelta['clock']); ?></td>
						<td><?php echo sprintf('%.1f', $stagedelta['cpu'] * 1000); ?></td>
						<td><?php echo sprintf('%d%%', $stagedelta['cpu'] * 100 / $totaldelta['clock']); ?></td>
						<td><?php echo $stagedelta['files']; ?></td>
						<td><?php echo sprintf('%.1f', $stagedelta['mysql'] * 1000); ?></td>
						<td><?php echo sprintf('%d%%', $stagedelta['mysql'] * 100 / $totaldelta['clock']); ?></td>
						<td><?php echo $stagedelta['queries']; ?></td>
						<td><?php echo sprintf('%.1f', $stagedelta['other'] * 1000); ?></td>
						<td><?php echo sprintf('%d%%', $stagedelta['other'] * 100 / $totaldelta['clock']); ?></td>
						<td><?php echo sprintf('%dk', $stagedelta['ram'] / 1024); ?></td>
						<td><?php echo sprintf('%d%%', $stagedelta['ram'] ? ($stagedelta['ram'] * 100 / $totaldelta['ram']) : 0); ?></td>
					</tr>
			<?php
				endforeach;
			?>
		</tbody>
		</table>

		<table class="extra-info">
180 181 182 183 184 185 186 187 188
		<tbody>
			<tr>
				<td class="debug-cell-files">
					<textarea class="debug-output" cols="40" rows="20"><?php
						foreach (get_included_files() as $file)
							echo qa_html(implode('/', array_slice(explode('/', $file), -3)))."\n";
					?></textarea>
				</td>
				<td class="debug-cell-queries">
Gideon Greenspan committed
189
					<textarea class="debug-output" cols="40" rows="20"><?php echo qa_html($this->databaseQueryLog)?></textarea>
190 191 192 193 194 195 196 197 198
				</td>
			</tr>
		</tbody>
		</table>
<?php
	}


	/**
199
	 * Return the difference between two resource usage arrays, as an array.
200 201 202 203 204 205 206 207 208 209 210 211
	 */
	private function delta($oldusage, $newusage)
	{
		$delta = array();

		foreach ($newusage as $key => $value)
			$delta[$key] = max(0, $value-@$oldusage[$key]);

		return $delta;
	}

}