Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Benchmarking a callback and get its return value in Laravel

You know Laravel always had the Illuminate\Support\Benchmark helper function which you can use to benchmark a callback and print it. For instance, if you want to benchmark a callback function, here’s how you can do it.

use Illuminate\Support\Benchmark;

Benchmark::dd(function () {
    sleep(2);
    
    // do something
});

// 2,000.116ms

It’s pretty handy when you want to measure the performance of a certain part of your code. But what if you want to benchmark a callback and get its return value (on top of the time it took) as well? Well, you can do that in the latest Laravel release.

Essentially, you can use the Benchmark::value method to benchmark a callback and get its return value like so.

use Illuminate\Support\Benchmark;

[$result, $duration] = Benchmark::value(function () {
    sleep(2);
    
    return 'Hello World!';
});

// $duration 2,000.116ms
// $result 'Hello World!'

The method returns two values in the form of an array. You can then use array destructuring to get the return value and the time it took to execute the callback respectively.

You might be wondering in which scenario this would be useful. Well, let’s say you want to benchmark a function, log something based on the time it took, and return the result of the function as well, this would be a perfect use case for this.

Here’s one such use case described by Tim MacDonald, the author of this feature.

public function list()
{
    [$response, $duration] = Benchmark::value(function() {
        return Http::get('https://external-service.com/list.json')
    });

    if ($duration > 1000) {
      Log::warning('external-service.com is running slow');
    }

    return $response->json();
}

As you can tell, in the above example, if the external service is running slow, it will log a warning and return the response as well using the Benchmark::value method.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?