Measuring the execution time of a PHP script

In this guide, we will show you how to measure the execution time of a PHP script.

This is also useful if you need to calculate how fast a certain operation takes. For example, a database query, a loop, or an API call.

Take a look at the following example:


//Save the microtime at the start of the script.
$startTime = microtime(true);

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

//Save the microtime at the end of the script.
$endTime = microtime(true);

//The result will be in seconds and milliseconds.
$seconds = $endTime - $startTime;

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

In the PHP code above, we measured the execution time by calculating the difference in microseconds between the start and end of the script.

We did this by using the microtime function.

Note that microtime returns a string by default, which isn’t useful for arithmetic. To force it to return a float number, we had to pass in a boolean true value.

If you are using PHP 5.4 or above, then you can use the REQUEST_TIME_FLOAT variable in the $_SERVER superglobal array.

This means that you will not need to manually save a start time at the top of your PHP code. Instead, you can do the following at the end:


//Your code is executed here.

//Get the execution time using "REQUEST_TIME_FLOAT".
$executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

This is 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.

Other tutorials on this subject suggest using the time function. However, PHP’s time function will only help you calculate the difference in seconds, which is far too imprecise for measuring performance. In the world of web development, there is a huge difference between 0.1 seconds and 0.9 seconds.

Please note that microtime will not measure how long your entire web page takes to load. It only calculates how long the PHP script took to execute on the server. Client-side elements like HTML, DOM manipulation, CSS files, JS files, and images will also affect the loading time.