Home » PHP » How to Calculate Execution Time in PHP

How to Calculate Execution Time in PHP

There are a lot of cases when you might need to measure code execution time. For example, you want to speed up your application and you need to find the slowest part or you want to benchmark several approaches to do something.

In this article, I will show you multiple ways to measure execution time in PHP and Laravel with different precision.

How to Measure Execution Time in PHP

1. Using time()

PHP language has the time() function that allows getting the current timestamp in seconds. It returns the number of seconds since January 1 1970 00:00:00 GMT. If this precision is enough for you, use the time() function to measure execution time PHP. Just save the current time in the $start variable before your code, and calculate the difference after it:

$start = time(); sleep(2); $duration = time() - $start; var_dump($duration);

Note, that the time is indicated in seconds and for many cases, this precision is not enough. Developers use this function for other purposes.

2. Using microtime()

This function works just like the time() function. It also returns a UNIX timestamp but returned in microseconds. It can return the data as a string where seconds and microseconds are separated by a space or as a float. Pass true as the first argument to get the time as a float.

microtime(); microtime(true);

You can use this value to measure execution time in seconds with microseconds:

$start = microtime(true); usleep(500000); $duration = microtime(true) - $start; var_dump($duration);

There are 1 000 000 microseconds in a second, so it may inconvenient to use them for measuring because you will get enormous numbers, which will make hard to compare them. I prefer using milliseconds. There are 1000 milliseconds in a second and it is enough when you work with small pieces of code. The simplest way to convert the return value of microtime() into milliseconds is to request a float and multiply it by 1000. For example:

$start = microtime(true) * 1000; usleep(500000); $duration = microtime(true) * 1000 - $start; var_dump($duration);

The precision of the float type is 14 digits. The seconds part takes 10 digits and leaves 4 digits for the microseconds part. It is enough for milliseconds.

3. Using hrtime()

If you want even more precision – you can measure the time in nanoseconds. It is a very short time interval.

  • One second has 1 000 000 000 nanoseconds (1e+9);
  • One millisecond has 1 000 000 nanoseconds (1e+6);
  • One microsecond has 1 000 nanoseconds;

Use the hrtime() function to do this. Note that the function returns high-resolution time, counted from an arbitrary point in time. It is not a Unix timestamp, so you can use it only during the current program execution, and you should not save it in the database or somewhere else. The function is available since PHP 7.3.

The hrtime() accepts a boolean as the first argument, which allows determining whether it should return an array or an integer. By default it will return an array where the first element contains seconds and the second contains nanoseconds:

hrtime(); /* * array:2 [ * 0 => 6111, //seconds * 1 => 45170383 //nanoseconds * ] */

If you pass true as the first argument, you will get an integer with the quantity of nanoseconds:

hrtime(true); // 6111045170783

You can measure the execution time in nanoseconds using this code:

$start = hrtime(true); time_nanosleep(0, 1000000); $duration = hrtime(true) - $start; var_dump($duration);

You can easily convert the time in nanoseconds to milliseconds or microseconds. Just multiply it by the required multiplier:

hrtime(true) * 1000; //microseconds hrtime(true) * 1000000; //milliseconds hrtime(true) * 1e6; //milliseconds too

4. Using Carbon

If you use any framework with the Carbon package installed, you can use it to measure time. Just create a new Carbon instance and get the timestamp in milliseconds:

Carbon::now()->getTimestampMs();

It will return an integer. Also, you can use the format() method, but be careful, this method returns a string:

Carbon::now()->format("Uu");

Let’s have a look at the example of measurement:

$start = Carbon::now()->getTimestampMs(); usleep(5000000); $duration = Carbon::now()->getTimestampMs() - $start; var_dump($duration);

Next, let’s have a look at how to check execution time PHP in Laravel.

5. Using symfony/stopwatch

It is a standalone package that allows to get execution time in milliseconds and memory usage in very simple way without any extra calculations. Install the package using the following command:

composer require symfony/stopwatch

Then, you can use the Symfony\Component\Stopwatch\Stopwatch class to measure execution time:

$stopwatch = new Stopwatch(); $stopwatch->start('eventName'); usleep(500000); $event = $stopwatch->stop('eventName'); echo (string) $event; //prints time in milliseconds and peak memory usage in MB as string echo $event->getDuration(); //500 echo $event->getMemory(); //prints peak memory usage

How to Measure Execution Time in Laravel

You can use all methods that are described above, but Laravel also has a Benchmark utility class since version 9.32.0. This class has measure() and dd() methods. They have the same signature:

Benchmark::measure(Closure|array $benchmarkables, int $iterations);

You can pass the closure function which you want to benchmark as the first argument. For example:

Benchmark::dd(function () { usleep(500000); });

This method displays execution time in microseconds using the dd() helper. If you want to get the value into a variable, use the measure() method:

$time = Benchmark::measure(function () { usleep(500000); }); dd($time);

If you want to benchmark and compare two or more functions, you can pass them as an array. For example:

Benchmark::dd([ "foo" => function () { usleep(500000); }, "bar" => function () { usleep(600000); }, ]);

Array keys will be used as names for measurement results. By default dd() and measure() methods perform only one iteration. But if you want to run the measurement multiple times, set the number of iterations as the second argument:

Benchmark::dd(function () { usleep(500000); }, 5);

You will get an average value as result.

Wrapping Up

In this article, we dove into time measurement in PHP and Laravel. As you can see, there are many ways to measure PHP script execution time, just choose the one that suits your situation best. What way do you prefer? Tell about it in the comments section below.

Your Reaction

Leave a Comment