
PROFILING WITH TIME() AND MICROTIME()
Code profiling is the analysis of various metrics related to code performance and efficiency.
If a PHP script is taking too much time to complete, it’s a good idea to profile the script to find out the cause.
The first thing to do is to isolate the piece of code (or the different pieces of code) responsible for the long execution time.
It could be an unoptimized function working on a large set of data, a slow SQL query, or a wrong iteration going out of control.
A very easy and straightforward way to perform this analysis is to use the time() and microtime() functions.
Both these functions return the current Unix Timestamp. time() returns it in seconds, while microtime() returns a float with microseconds too.
To check the execution time of a piece of code you need to:
- Save the current time with time() or with microtime() before the code you want to profile.
- After the code, call time() or microtime() again and calculate the difference from the previously saved value.
- That is the execution time in seconds 😉
If the execution time is more than a few seconds you can use time(), otherwise it’s usually more useful to use microseconds.
This is a practical example:
<?php
$start = microtime(TRUE);
/* Start of the code to profile */
for ($a = 0; $a < 10000000; $a++)
{
$b = $a*$a;
}
/* End of the code to profile */
$end = microtime(TRUE);
echo "The code took " . ($end - $start) . " seconds to complete.";
If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.
If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!
Alex
Hey maybe take a look at this easy PHP Helper Class:
https://github.com/leo-lobster/php-timetrack
Interesting, thank you for sharing.
This is incorrect. This will report the *seconds* that it took to complete the script, not *microseconds*. See here: https://3v4l.org/JkMjp
Hey Chris,
you’re right! I fixed the post, thanks!