How to measure PHP page load time
Website’s loading speed is an important factor in the success of a website. It is also considered in the search engine ranking by Google. So, It is advisable to have a website which loads slow and takes server resources. So It is a good idea to measure the speed of your PHP code to check which part is taking time. For checking the load time of a web page, there are lots of tools available. But having your own will help you debug lots of things on your code.
For checking the execution time of PHP codes you can do this with the help of microtime() PHP function. This will help you to set the start and end time to measure the actual time taken by a script.
Put this part of the code at the start of a webpage. This part will set the start marker when the page was actually started loading.
<?php $time = microtime(); $time = explode(' ', $time); $time = $time + $time; $start = $time; ?>
Put this part of the code at the end of the webpage. This part will set the end marker and then calculate the time difference to exactly measure the time taken by the PHP code in execution.
<?php $time = microtime(); $time = explode(' ', $time); $time = $time + $time; $finish = $time; $total_time = round(($finish - $start), 4); echo 'Page generated in '.$total_time.' seconds.'."n"; ?>
This code will tell you the time taken by the web page in loading.
You can use this code to measure the time and then put it at the bottom of the page if you want users to know how much time it took to generate the page. Just like Google shows the time in fetching search results.
You can use this to know the amount of time taken by each piece of code to know which script is taking time. This can help you understand what section is taking more time and needs optimization.