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:

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:

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.

Comments

comments