How to calculate page load time in PHP ?

Page load time is a way  to  check fastest  and slowest  page in your website or web application. Many websites use this  feature in the end of page. If you are building internal analytics to track  user behaviors then page load time is  a must feature  to use.

So how we calculate  page load time in PHP. There is a function microtime() in PHP that we will use for the page load time. There is 2 ways to calculate :

Method 1 – Define start time at the top of script and end time at the bottom of script. And subtract start time from end time. You will get total script load time in seconds.

 $start = microtime(true);
 
//Script logic
//Script logic

$end = microtime(true);
$loadTime = $end - $start;  // PAGE LOAD TIME IN SECONDS

Method 2 – If you are using 5.4 +, then there is $_SERVER variable have a REQUEST_TIME_FLOAT which eliminates the need to of start time. So your code will be in the end of your script.

// PHP Script
// Logic
//

$loadtime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];   // PAGE LOAD TIME IN SECONDS

Please try these methods and let me know if you face any problem in comment section. Thanks

Leave a Reply