You are viewing...

Using PHP’s Microtime to measure page generation time

Updated on December 23, 2010 at the 20th hour
Posted under:

DISCLAIMER: All views are considered my own and you should not draw any conclusions on associates.

There are two ways of using the microtime function to measure page generation time.

The first way consists of using microtime() without any arguments leaving its only argument to default to false. The first and only argument is a bool (defaulted to false) determining whether the function should return a float. What does this float represent? Isn’t it the actual time using a float, so why is it defaulted to false? I suppose that people might want the actual seconds and the microseconds separate, which is why the default is false.

First way (Using arrays):
$startTime = explode(‘ ’, microtime()); // Notice there are no arguments// whatever code goes here to generate the page

$counter = 0;

while(true){ if($counter++ == 1000){

break;

}

}$endTime = explode(‘ ’, microtime());$pageGenerationTime = ($endTime[0] + $endTime[1]) – ($startTime[0] + $startTime[1]);printf(“Page generated in %.8f seconds”, $pageGenerationTime); // I use 8 decimal places, though you really don’t need that kind of precision.

Second way (using floats):
$startTime = microtime(true); // Notice the true value used here// whatever code goes here to generate the page

$counter = 0;

while(true){ if($counter++ == 1000){

break;

}

}$endTime = microtime(true);$pageGenerationTime = $endTime – $startTime;printf(“Page generated in %.8f seconds”, $pageGenerationTime); // I use 8 decimal places, though you really don’t need that kind of precision.

That’s just using microtime() to measure page generation. What’s the performance difference between these two? There is a performance difference of 1.5-3.0 times from the second one to the first. I recommend using the second way to generate page time over the first way, if you do not care for the separation of microseconds from the seconds itself.

-- The PHP manual actually talks about this and haven’t looked at the microtime function page since PHP 4, so I did not know the PHP manual shows these two use cases already. The bool argument is defaulted to false for backwards compatibility reasons from what I see. Anyway, if you are not on PHP 5 already, I suggest you upgrade of take advantage of this feature and more.
You just read "Using PHP’s Microtime to measure page generation time". Please share if you liked it!
You can read more recent posts here.