How to check the execution time of a php script

You have the feeling your website is slow? Some process is taking too long, something is not loading fast enough? Of course, there might be a script or maybe just a few lines of php slowing it down – but which part of the script is it? If you are witnessing for example speed problems with a WordPress Plugin, chances are that the plugin runs some loop inside a loop and/or maybe sending too many database queries. Reducing the number of database mySQL queries can dramatically speed up your page load time – but that will be subject of a different article. Anyways – all we need to know now is that there are ways to find out, which script or which plugin is executing slow – and how long it actually takes, to execute that particular piece of code.

Debugging or optimizing a script can be a time consuming task to do – so we’ll focus on those parts, that are the ‘most expensive’ ones – meaning the slowest ones. To find ‘time bandits’ inside your code all you basically have to do is start a timer before the suspicious script / plugin / module is executed – and then stop the timer once the script has done its job. And with PHP at hand it is not really complicated to measure the time that has past executing a piece of code – PHP code that is. Microtime to the rescue!

First you need to define a variable for the timer and start the timer before the script is executed like this:

$start_timer = microtime(true);

Then you stop the timer, after the script is executed like this:

$time_passed = microtime(true) - $start_timer;

You could then print the time that passed with a simple echo command:

echo("The script needed ".$time_passed." seconds to execute.");

If you want to round that number off to two positions behind the decimal point, you simply add the round command like this:

echo("The script needed ".round($time_passed, 2)." seconds to execute.");

So if you put everything together, it could look like this:

$start_timer = microtime(true);

// the suspicious code goes here
while … {


$time_passed = microtime(true) - $start_timer;

echo("The script needed ".round($time_passed, 2)." seconds to execute.");

PS: You may ask if speed optimization pays off? Is loading speed a SEO criteria? Is a slow loading website bad for SEO? And/or is a slow site bad for UX? All these questions can be answered YES. Good luck!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.