Benchmark PHP Code With microtime()

Sometimes is is necessary to see how long your PHP code runs for. This can be done using the following function and examples. This will convert the result of the php function microtime() into a float value.

function getmicrotime($t){
  list($usec, $sec) = explode(" ",$t);
  return ((float)$usec + (float)$sec);  
}

Use this function to see how long something runs for. At the start of the code call the microtime() function and store the result at the start. At the end store the result of the microtime() function as the end and then use the two values to figure out how long the code took to run.

$start = microtime();
$a = array();
for($i=0;$i<10000;$i++) {
  $a[] = $i;
}
$end = microtime();
$time = (getmicrotime($end) - getmicrotime($start));

The bottom line when benchmarking is to run the same bit of code lots of times. If you run the code once or twice you will find a different result every time. The best thing to do is run the code more than 100 times and take an average.

Comments

As of PHP 5 it is possible to bypass the getmicrotime() function by simply passing true to the microtime() function.
$start = microtime(true);
So the code above can be shortened to:
$start = microtime(true);
$a = array();
for($i=0; $i10000; $i++) {
  $a[] = $i;
}
$end = microtime(true);
$time = $end - $start;
Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.