Home

Share via:

PHP: Track Execution Time

How to track execution time using PHP microtime.

119 views

Edited: 2020-05-29 18:36

Track execution time, PHP

To track the execution time of a PHP script—or just a part of some PHP code—we should make a timestamp right before executing the relevant code, and then again right after the code finishes.

This is quite useful for performing simple benchmark testing of code. Often we will find that there is multiple ways to do the same thing when programming, and this is also true when we are coding in PHP. Some PHP functions are simply faster than others.

For the most part, the speed difference is not going to matter unless you are handling several thousands—or even millions—of requests. But, if we know something is faster, then why not use the most efficient method from the beginning? Very often, it is actually obvious what will be the fastest way.

A simple speed test can be performed like this:

$start_time = microtime(true);

// Your code here

$time_spent = microtime(true)-$start_time;

echo $time_spent;

When the parameter of microtime is set to true, the result will be returned in seconds. If you leave out the parameter, a string will be returned instead of a float, which can not be used easily in calculations; hence why microtime(true) is used instead of clean microtime().

Determining which is faster

In many cases, a single run is not to be enough for us to tell which piece of code is the fastest, since the difference is minuscule.

So, in order to notice a difference, we should combine this with a while or for loop, and then run the test at least a million times:

$start_time = microtime(true);

for ($i = 0; $x <= 1000000; $i++) {
  // Your code here
}

$time_spent = microtime(true)-$start_time;

echo $time_spent;

Comments