Simple PHP execution time monitoring

5th October 2008 12:00

We've all heard about optimising the user's experience on the client-side, but what about on the server?

When building out play.tm we decided we needed a tool that broke down how the PHP script generated the page and displayed how long each element took to generate. We could then optimise the worst performing code. We called it 'speedtrap'. So, here is the code:

In the top of your page:


$st_StartTime = microtime(true);
$speedTraps = array();

The function:


function speedTrap($trapName) {
	global $st_StartTime,$speedTraps;
	$difference = microtime(true) - $st_StartTime;
	$speedTraps[$trapName]=$difference;
}

At every point where you want put a speedtrap, with a description of what has happened in the code:


speedTrap("Done some part of the page");

Then, at the end of the page call this function:


function speedTrapBars() {
	
	global $siteVars,$speedTraps;
	
	if ($siteVars['showSpeedTrap']) {
	
		?>
		<h1>SpeedTrap!</h1>
		<dl id="speedtrap">
		<?
	
		$lastValue = 0;
	
		foreach ($speedTraps as $key => $value) {
			?>
				<dt><?=$key?></dt>
				<dd style="width:<?=round($value*1000)?>px"><span><?=round(($value-$lastValue)*1000,3)?>ms</span></dd>
			<?
			$lastValue = $value;
		}
		?>
		<dt>Server Done</dt>
		<dd class="last" style="width:<?=round($lastValue*1000)?>px"><?=$lastValue*1000?>ms</dd>
		<?
		echo "</dl>";
	
	}
	
}

But wait! There's more! Some bonus CSS:


#speedtrap {
	font-size:1.1em;
	margin:5px;
}
#speedtrap dt, #speedtrap dd {
	float:left;
	margin-bottom:1px;
}
#speedtrap dt {
	width:100px;
	clear:left;
}
#speedtrap dd {
	background:lightgray;
	padding:2px;
}
#speedtrap .last {
	background:gray;
}

Jason Cartwright RSS Feed

About

Jason is a freelance web developer based in London.

My clients include numerous startups & agencies, Google, YouTube, FHM, Nickelodeon, Volvo & the BBC.

I also co-own Ferrago Ltd, who publish videogames content to around 7m consumers monthly.

Links

Colophon