PHP: Calculate the execution time of a script.

This is a quick tutorial on how to calculate the execution time of a PHP script. i.e. How long did it take the script to run from start to finish; including database queries, API calls, etc?

Firstly, I think it is worth pointing out that this will not tell you how long it took for a given web page to load. When we say “execution time”, we are talking about the time it took for the server application to process the user’s request and return a response. This method will not let you know how long it took for images, CSS files and other resources to load in the user’s browser (these resources are loaded on the client side, which makes it a little more difficult to calculate).

An example PHP code snippet:


//Store the micro time so that we know
//when our script started to run.
$executionStartTime = microtime(true);

//Example code.
$pdo->query("SELECT id FROM users WHERE email_verified = 0");

//At the end of your code, compare the current
//microtime to the microtime that we stored
//at the beginning of the script.
$executionEndTime = microtime(true);

//The result will be in seconds and milliseconds.
$seconds = $executionEndTime - $executionStartTime;

//Print it out
echo "This script took $seconds to execute.";

As you can see, we basically just used the microtime function to compare the microseconds that passed between the start of our script and the end of our script. We gave it a TRUE value because we wanted the result as a float number (by default, it returns a string value).

If you are using PHP 5.4 or above, then you’ll be happy to know that the start time is already available in the $_SERVER superglobal array. i.e. Instead of manually storing the start time, you can simply do this at the end of your PHP scripts:


//My code is executed here.

//At the bottom of my PHP script, I can get the execution
//time like so, using "REQUEST_TIME_FLOAT".
$executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

This is obviously a cleaner solution than the one outlined in the first example, as it means that you don’t need to insert code into the top of your scripts.