Home > Tutorials > PHP Tutorials > Display Page Loading Time

Display Page Loading Time

Have you ever noticed that lots of websites feature some text towards the very bottom of a page saying “Page took x.xxx seconds to load”? It’s a pretty simple thing to make and gives your site something that we all love … stats! So today we’ll take a look at how to accomplish this through the use of PHP. First off let’s outline what we’ll need to do for this:

  1. Get the time in micro-seconds using the function: microtime().
  2. Turn the micro-time into an array using the explode() function.
  3. Add the two parts of the array together (the micro-seconds to the seconds).
  4. Repeat steps 1,2 and 3 for the bottom of the page.
  5. Find the total loading time by taking the time taken at the end of the page from the time taken at the top of the page.
  6. Round the microtime and return it to the browser.

So we start with measuring the time at the top of the page – so right after you’re opening <HTML> tag go ahead and insert the following code:

<? 
$m_time = explode(" ",microtime()); 
$m_time = $m_time[0] + $m_time[1]; 
$starttime = $m_time; 
?>

We have now completed the first 3 steps – and stored the starting time into a variable called starttime. Now we just need to repeat these 3 steps at the very bottom of the page, compare the 2 times, and echo out our display to the browser. So place the following at the bottom of the page where you wish to display the loading time:

<? 
$round = 3;// The number of decimal places to round the micro time to. 
$m_time = explode(" ",microtime()); 
$m_time = $m_time[0] + $m_time[1]; 
$endtime = $m_time; 
$totaltime = ($endtime - $starttime); 
echo "Page loading took:". round($totaltime,$round) ." seconds"; ?>

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...

  • JuniorNTR

    Pretty simple ..

    I always thought pHP is hard .. with server side scripting and other latin functions involved ..

    thank you for the heads up ..

  • Franky Chacha

    Hey, this shows the loading time right .. cool ..

    Do you have something to reduce the loading time? My site loads slow due to videos and js .. how to manage? how to create lite versions?

    • vivekmanapuram

      @frankychacha:disqus, I too am looking for creating a lite version .. just like Youtube light .. but have no idea how .. and I would also like to have the ability to change between standard and lite versions ..