Calculate script execution time in PHP

In this article, we will talk about script execution time in PHP. We will use PHP microtime function to calculate time. microtime function return current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

You may need to calculate execution time of PHP scripts for various purposes such as calculate page loading speed or image upload time and so on. Calculating php scripts execution time is a simple process of subtraction between two times: script start execution time and script end execution time.


$executionTime = $endTime - $startTime;
echo 'Total Time taken for execution: '. $executionTime.' seconds.

As you can see, we store the starting time and ending time in two separate variables $startTime and $endTime. Then, we did a subtraction between these times and displayed the result.

If you are using PHP 5.4 or above, you can use a $_SERVER global array with REQUEST_TIME_FLOAT index. So, you don’t need to calculate starting time. You can directly calculate time difference by below line at the end of your script.

for($i=0; $i<1000000; $i++)
    //do some stuff

echo 'This script took ' . microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'] . ' seconds to execute';

Note that the timestamp returned is "with microseconds", not "in microseconds". This is especially good to know if you pass 'true' as the parameter and then calculate the difference between two float values. The result is already in seconds; it doesn't need to be divided by a million.

Read More Articles


Please enter your comment!
Please enter your name here