Calculate Page Load Time in PHP

Sometimes we need to calculate how long does it take to load a web page which we create from code.

Website loading speed is very much important both from user and search engine point of view.

If a website takes too much loading time then users don’t wait for it. So by checking how much time your website is taking to load, you can optimize the speed and performance.

So, In this tutorial, I am going to show you how you can calculate page load time in PHP. To calculate page load time we have to create a function using microtime inbuilt function.

Here, “microtime” gives the current Unix timestamp with microseconds.

Create a User Defined Function

Create a user defined function to get the current time.

<?php
function getTime()
{
 return array_sum(explode(” “,microtime()));  
}

$startTime = getTime();

// All your code
for ($i=0; $i< 10000000; $i++){
}

$endTime = getTime();

$timeTaken = round(($endTime – $startTime),2);

echo “Page loaded in $timeTaken seconds”;
?>

We have to use this function two times on a webpage, one at the beginning and another at the end of the webpage.

We are using two variables to store start time and end time respectively. In the middle, we write all code for functionality.

In the end, subtracting the start time from the end time to get the time taken to load a web page.

Let’s see how to use this script in PHP file to calculate page load time.

Create a PHP file and define markup and scripting.

<?php
function getTime()
{
 return array_sum(explode(” “,microtime()));  
}

$startTime = getTime();
?>

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<meta name=”description” content=”Page Load time in PHP”>
<title>Page Load Time PHP – PhpCluster</title>
</head>

<body>
<h1>Page Load Time in PHP</h1>

<p>This is sample paragraph</p>

<?php
// All your code
for ($i=0; $i< 10000000; $i++){
}
?>

</body>
</html>

<?php
$endTime = getTime();

$timeTaken = round(($endTime – $startTime),2);

echo “Page loaded in $timeTaken seconds”;
?>

Conclusion

In this tutorial, you have learned how to show page loading time using PHP.

The post Calculate Page Load Time in PHP appeared first on PhpCluster.

Flatlogic Admin Templates banner

Leave a Reply

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