Display page load time in PHP

You must have noticed a lot of site display this message "Page generated in XX.XX seconds" at the bottom of the page. It is very easy to make and I will show in this post how to do so. It is a tool which gives you information on how optimized and fast is your site. Also you can easily identify performance issues by using this as it tells you how efficient your code is. Moreover website visitor's love this kind of statistics. So how do we get this time related information? The most efficient way to do this is that you store the system time at the beginning and end of your PHP code in two separate variables and then subtract them to get the total time taken to execute your code.

For getting current system PHP has an in-built function known as microtime(). It returns the current Unix timestamp along with milliseconds in string format - "msec sec" i.e. milliseconds followed by seconds. We can also give it an optional boolean parameter known as get_as_float and if this parameter is true then the function returns both the portions of the string (milliseconds and seconds) are returned as a float value in unit of seconds (i.e. it adds them up).

So in order to measure the page generation time add the following code to the beginning of your PHP code -


$start_time = microtime(TRUE);


At the end of your PHP code add the following snippet -


$end_time = microtime(TRUE);

$time_taken = $end_time - $start_time;

$time_taken = round($time_taken,5);

echo 'Page generated in '.$time_taken.' seconds.';



And now if you will run this, it will print the page generation time in seconds. For instance on running this code snippet on this page we get the following output -

Page generated in 0.1548 seconds.

Here round() function has been used to round up the value of page generation time to five digits after the decimal point. Just add the above snippet to header and footer of your website and it will give you the page generation time which you can display at the bottom of your website.