Benchmark PHP Code With microtime()

2nd February 2008 - 2 minutes read time

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.

  1. function getmicrotime($t){
  2. list($usec, $sec) = explode(" ",$t);
  3. return ((float)$usec + (float)$sec);
  4. }

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.

  1. $start = microtime();
  2. $a = array();
  3. for($i=0;$i<10000;$i++) {
  4. $a[] = $i;
  5. }
  6. $end = microtime();
  7. $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.


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:
  1. $start = microtime(true);
  2. $a = array();
  3. for($i=0; $i

Add new comment

The content of this field is kept private and will not be shown publicly.