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 need to find the slowest part or benchmark several approaches to do some task.
In this article, I will show you multiple ways to measure execution time in PHP and Laravel with different precision.
Table of Contents
How to Measure Execution Time in PHP
Before measuring time, let’s look at what additional functions we’ll be using. In this article, I will use the sleep() function and other similar functions to show how PHP measures time. Here are these function and their description:
- sleep($seconds) – wait for a specified number of seconds;
- usleep($microseconds) – wait for a specified number of microseconds;
- time_nanosleep($nanoseconds) – wait for a specified number of nanoseconds;
It’s also worth mentioning how all these units of time are related to each other:
Time | One Second | One Millisecond | One Microsecond | One Nanosecond |
Seconds | 1 | |||
Milliseconds | 1 000 | 1 | ||
Microseconds | 1 000 000 | 1 000 | 1 | |
Nanoseconds | 1 000 000 000 | 1 000 000 | 1 000 | 1 |
1. Using time()
PHP language has the time() function that allows you to get the current timestamp in seconds. It returns the number of seconds that have passed since January 1, 1970, 00:00:00 GMT. If this precision is enough for you, use the time() function to measure the execution time of a PHP script. Just save the current time in the $start variable in beginning of your script or code, and then get the timestamp in the end of your script or code and calculate the difference:
time.php<?php
$start = time();
sleep(2);
$duration = time() - $start;
var_dump($duration); //seconds
Note that the time is returned in seconds. More than this, precision is needed in many cases. Usually, developers utilize this function for other purposes.
2. Using microtime()
This function works just like the time() function. It also returns the current UNIX timestamp but 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 in the first argument to get the time as a float.
…microtime(); // 0.97411700 1690291070
microtime(true); // 1690291070.9741
You can use the float value to measure execution time in microseconds:
time.php<?php
$start = microtime(true);
usleep(500000); // wait 0.5 sec
$duration = microtime(true) - $start;
var_dump($duration); //seconds
There are 1 000 000 microseconds in a second. So it may be inconvenient to use time in nanoseconds for measuring because you will get enormous numbers, making it hard to compare them. I prefer using milliseconds. There are 1000 milliseconds in a second, which is enough for most cases. The simplest way to convert the return value of microtime() into milliseconds is to get a float and multiply it by 1000. For example:
time.php<?php
$start = microtime(true) * 1000;
usleep(500000); // wait 0.5 sec
$duration = microtime(true) * 1000 - $start;
var_dump($duration); //milliseconds
The precision of the float type is 14 digits. The seconds part takes ten digits and leaves four 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).
Use the hrtime() function to get time in nanoseconds. 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 specifying 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 number of nanoseconds:
…hrtime(true); // 6111045170783
You can measure the execution time in nanoseconds using this code:
time.php<?php
$start = hrtime(true);
time_nanosleep(0, 1000000); // wait 1 millisecond
$duration = hrtime(true) - $start;
var_dump($duration); //nanoseconds
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 note that this method returns a string:
…Carbon::now()->format("Uu");
Let’s have a look at the example of measurement:
time.php<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
$start = Carbon::now()->getTimestampMs();
usleep(5000000); // wait 5 seconds
$duration = Carbon::now()->getTimestampMs() - $start;
var_dump($duration); //milliseconds
5. Using symfony/stopwatch
It is a standalone package that allows to get execution time in milliseconds and memory usage in a straightforward 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:
time.php<?php
require 'vendor/autoload.php';
use Symfony\Component\Stopwatch\Stopwatch;
$stopwatch = new Stopwatch();
$stopwatch->start('eventName');
usleep(500000);
$event = $stopwatch->stop('eventName');
echo (string) $event . "\n"; //prints time in milliseconds and peak memory usage in MB as string
echo $event->getDuration() . "\n"; //500
echo $event->getMemory() . "\n"; //prints peak memory usage
Next, let’s have a look at how to check the execution time PHP in Laravel.
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:
…\Illuminate\Support\Benchmark::measure(Closure|array $benchmarkables, int $iterations);
You can pass the closure function which you want to benchmark as the first argument. For example:
app/Console/Commands/MeasureTimeCommand.phpuse Illuminate\Support\Benchmark;
app/Console/Commands/MeasureTimeCommand.phpBenchmark::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:
app/Console/Commands/MeasureTimeCommand.php$time = Benchmark::measure(function () {
usleep(500000);
});
dd($time);
You can read more about this Laravel feature in the official documentation.
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.