Benchmark.php
TLDR
The Benchmark.php
file in the Illuminate\Support
namespace contains a class called Benchmark
that provides methods for measuring the performance of PHP callables.
Methods
measure
This method measures the execution time of a callable or an array of callables over a given number of iterations. It takes as input a closure or an array of closures to be benchmarked, and the number of iterations. The method returns an array of average execution times for each callable if an array was provided, or a single average execution time if a closure was provided.
value
This method measures the duration of a single execution of a callable and returns the duration and the result. It takes as input a callable and returns an array with two elements: the result returned by the callable and the duration in milliseconds.
dd
This method measures the execution time of a callable or an array of callables over a given number of iterations and then dumps the result and terminates the script execution. It takes as input a closure or an array of closures to be benchmarked, and the number of iterations.
Classes
There are no classes in this file.
<?php
namespace Illuminate\Support;
use Closure;
class Benchmark
{
/**
* Measure a callable or array of callables over the given number of iterations.
*
* @param \Closure|array $benchmarkables
* @param int $iterations
* @return array|float
*/
public static function measure(Closure|array $benchmarkables, int $iterations = 1): array|float
{
return collect(Arr::wrap($benchmarkables))->map(function ($callback) use ($iterations) {
return collect(range(1, $iterations))->map(function () use ($callback) {
gc_collect_cycles();
$start = hrtime(true);
$callback();
return (hrtime(true) - $start) / 1000000;
})->average();
})->when(
$benchmarkables instanceof Closure,
fn ($c) => $c->first(),
fn ($c) => $c->all(),
);
}
/**
* Measure a callable once and return the duration and result.
*
* @template TReturn of mixed
*
* @param (callable(): TReturn) $callback
* @return array{0: TReturn, 1: float}
*/
public static function value(callable $callback): array
{
gc_collect_cycles();
$start = hrtime(true);
$result = $callback();
return [$result, (hrtime(true) - $start) / 1000000];
}
/**
* Measure a callable or array of callables over the given number of iterations, then dump and die.
*
* @param \Closure|array $benchmarkables
* @param int $iterations
* @return never
*/
public static function dd(Closure|array $benchmarkables, int $iterations = 1): void
{
$result = collect(static::measure(Arr::wrap($benchmarkables), $iterations))
->map(fn ($average) => number_format($average, 3).'ms')
->when($benchmarkables instanceof Closure, fn ($c) => $c->first(), fn ($c) => $c->all());
dd($result);
}
}