| 1 |
<?php |
| 2 |
|
| 3 |
namespace Illuminate\Support; |
| 4 |
|
| 5 |
use Closure; |
| 6 |
use Illuminate\Support\Traits\Macroable; |
| 7 |
|
| 8 |
class Benchmark |
| 9 |
{ |
| 10 |
use Macroable; |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
public static function measure(Closure|array $benchmarkables, int $iterations = 1): array|float |
| 20 |
{ |
| 21 |
return Collection::wrap($benchmarkables)->map(function ($callback) use ($iterations) { |
| 22 |
return Collection::range(1, $iterations)->map(function () use ($callback) { |
| 23 |
gc_collect_cycles(); |
| 24 |
|
| 25 |
$start = hrtime(true); |
| 26 |
|
| 27 |
$callback(); |
| 28 |
|
| 29 |
return (hrtime(true) - $start) / 1_000_000; |
| 30 |
})->average(); |
| 31 |
})->when( |
| 32 |
$benchmarkables instanceof Closure, |
| 33 |
fn ($c) => $c->first(), |
| 34 |
fn ($c) => $c->all(), |
| 35 |
); |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
public static function value(callable $callback): array |
| 47 |
{ |
| 48 |
gc_collect_cycles(); |
| 49 |
|
| 50 |
$start = hrtime(true); |
| 51 |
|
| 52 |
$result = $callback(); |
| 53 |
|
| 54 |
return [$result, (hrtime(true) - $start) / 1_000_000]; |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public static function dd(Closure|array $benchmarkables, int $iterations = 1): never |
| 65 |
{ |
| 66 |
$result = (new Collection(static::measure(Arr::wrap($benchmarkables), $iterations))) |
| 67 |
->map(fn ($average) => number_format($average, 3).'ms') |
| 68 |
->when($benchmarkables instanceof Closure, fn ($c) => $c->first(), fn ($c) => $c->all()); |
| 69 |
|
| 70 |
dd($result); |
| 71 |
} |
| 72 |
} |