Track execution time of a script in PHP
This article demonstrates how to track the execution time of a script in PHP.
You can use the in-built PHP function microtime() to track the script execution time in PHP. It returns the current time in seconds since the Unix epoch, accurate to the nearest microsecond. If the second parameter is set to true
, then it returns a float instead of a string in “msec sec” format.
You can invoke the microtime()
function at the start of the script and call microtime()
again immediately after the script execution. Then the difference between the return values of these two calls is the elapsed time in seconds. Note that the returned time is the wall-clock time and not the CPU execution time. In other words, the elapsed time measured with microtime()
might not be accurate and can depend on external factors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php /* START SCRIPT */ $start = microtime(true); // sleep for 1 second usleep(1000000); /* END SCRIPT */ // measure time in seconds $time = microtime(true) - $start; echo "Time taken: $time seconds"; ?> |
Alternatively, you can use REQUEST_TIME
from the $_SERVER superglobal array to get the timestamp of the start of the request. To get the timestamp with microsecond precision, consider using REQUEST_TIME_FLOAT
. This eliminates the need for microtime()
call at the start of your script. The following solution shows how to use REQUEST_TIME_FLOAT
to get the elapsed time in seconds from the beginning of the script, with microsecond precision.
1 2 3 4 5 6 7 8 9 10 |
<?php // sleep for 1 second usleep(1000000); // measure time in seconds $time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; echo "Time taken: $time seconds"; ?> |
That’s all about tracking the execution time of a script in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)