Skip to content

Script timing in PHP

It you have spent time on sites that use a CMS system as a back-end, you may have noticed a line towards the bottom that tells you how long that page took to generate. While not always useful for the end user, it is very useful to you as a the developer. It gives you a quanitative look at how quickly your pages are being generated, and you can use this to determine if your code or queries need to be modified to work more quickly or if your server is overloaded.

To do this, we are going to use the PHP command Microtime(). Microtime() returns the UNIX timestamp. The timestamp is the number of seconds since January 1, 1970, although that really isn’t important for this. It’s just a good bit of trivia to know at geek parties :-)

What is important to remember about microtime() is that it returns the microseconds and whole seconds separated by a space, so you’ll need to explode out the two into an array and then add them together. PHP version 5 adds a option to return the value as a float, but I don’t have version 5 installed, so I can’t give any thoughts on that.

Near the top of your page add the code
$starttime = microtime();

This will fill the variable $starttime with the current timestamp. At the end of the page add
$endtime = microtime();
$starttime = explode(" ", $starttime);
$starttime = $starttime[1] + $starttime[0];
$endtime = explode(" ", $endtime);
$endtime = $endtime[1] + $endtime[0];
$totaltime = $endtime - $starttime;
echo "Page was generated in ".$totaltime." seconds";

These commands do not necessarily have be the very first and very last line, but they should be in a place before and after any really intensive computing scripts (database queries, text file reads, etc).

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *