Site icon Technopoints

Calculate Page Load Time in PHP

Calculate Page Load Time in PHP

Hey Technoz,  In this tutorial we are going to learn how to calculate page load time in PHP. To calculate page load time you need to put two times, the start time at the beginning of the page and the end time at the end of the page or php script. The reason behind writing this code in php and not in javascript is to avoid limitation like it will not measure DNS looking, initial latency and server response time.

Calculate Page Load Time in PHP

The following code loadtime.php  contents a sample dummy loop (consider it as your page php code) where you can put your php code by replacing the loop.

In this, we are using microtime function which is used to returns the current Unix time-stamp with microseconds.

We are storing two times at two variables $start and $finish. At the start of the code we call the get_time function which return the start time and store it to $start and at the end of the code we get the end time and store it to the $finish.

At the end we subtracts start time from end time and get the resulted output in $total_time.

<?php

function get_time() {

    $time = microtime();

    $time = explode(' ', $time);

    $time = $time[1] + $time[0];

    return $time;

}

$start = get_time();

?>
<!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">
    <title>Technopoints | Page load time</title>
<h1>Technopoints | Page Load Time in PHP</h1>

<p>This is sample paragraph</p>


<?php
for($i=0;$i<100000;$i++) { 
//a sample dummy loop
}
?>

<?php

$finish = get_time();

$total_time = round(($finish - $start), 4);

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

?>

Here explode() function breaks a string into an array.

round() function is use to round up the value of page generation time to five digits after the decimal point.

Now, when you run this code you will know the page load time as shown in following snapshot.

In this tutorial we have learn to Calculate Page Load Time in PHP in any php script.

If you have any doubts regarding to this tutorial feel free to ask in the comment section below.

To catch even more knowledgeable and easy understandable tutorials please subscribe to get email notification.

Download Source Code

Exit mobile version