Benchmark PHP Code With microtime()

2 February, 2008 | PHP

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

Pingback from PHP Function To Work Out Average Values In Array | Talk In Code
Date: March 11, 2008, 5:25 pm

[...] test but without using function calls, just including the code that works out the averages in the benchmark timing function. It turns out that the first function is slightly faster when using short arrays, but is still [...]

Pingback from Array Sorting Functions In PHP | Talk In Code
Date: April 1, 2008, 3:07 pm

[...] You can test how long your algorithm takes to run by using the PHP benchmarking function. [...]

Pingback from Single Quotes Or Double Quotes With PHP? | Talk In Code
Date: July 9, 2008, 9:22 am

[...] the PHP benchmarking function I tested each of these mechanisms to see which was the fastest. Because each test is very quick I [...]

Write a comment