Benchmarking and testing your PHP script with microtime

September 10, 2010

When you're building a new website you often code it 'on-the-fly'. That's to say, strapping in new features here and there until it does exactly what you want - but leaving a mess that needs to be optimised.

One of the best ways of testing your site for scalability (other than getting huge traffic straight away) is to test how long your PHP scripts take to parse. We can do this by comparing the time at the start and end of a script to give us the processing time.

The PHP manual shows the following example:

$time_start = microtime(true);
// Script you want to test here
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";

But I prefer this for readability (I put this in a common include so I can test the whole site by simply calling some functions...see below):

function starttime() {
  $r = explode( ' ', microtime() );
  $r = $r[1] + $r[0];
  return $r;

function endtime($starttime) {
  $r = explode( ' ', microtime() );
  $r = $r[1] + $r[0];
  $r = round($r - $starttime,4);
  return '<strong>Execution Time</strong>: '.$r.' seconds<br />';

To use this in a script all we'd need to do is place this at the start and end, and do a simple calculation. For example (using sudo code):

$start = starttime();
// Script you want to test here
echo endtime($start);

This will help you discover bottlenecks in your script - there are a load of things you can do to optimise your script; and I find that using functions as above don't add extra complication to your script.

Profile picture

From Dave, who writes to learn things. Thoughts and views are his own.

© 2024, withdave.