| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Illuminate\Support;
|
|
|
4 |
|
|
|
5 |
use Closure;
|
|
|
6 |
|
|
|
7 |
class Benchmark
|
|
|
8 |
{
|
|
|
9 |
/**
|
|
|
10 |
* Measure a callable or array of callables over the given number of iterations.
|
|
|
11 |
*
|
|
|
12 |
* @param \Closure|array $benchmarkables
|
|
|
13 |
* @param int $iterations
|
|
|
14 |
* @return array|float
|
|
|
15 |
*/
|
|
|
16 |
public static function measure(Closure|array $benchmarkables, int $iterations = 1): array|float
|
|
|
17 |
{
|
|
|
18 |
return collect(Arr::wrap($benchmarkables))->map(function ($callback) use ($iterations) {
|
|
|
19 |
return collect(range(1, $iterations))->map(function () use ($callback) {
|
|
|
20 |
gc_collect_cycles();
|
|
|
21 |
|
|
|
22 |
$start = hrtime(true);
|
|
|
23 |
|
|
|
24 |
$callback();
|
|
|
25 |
|
|
|
26 |
return (hrtime(true) - $start) / 1000000;
|
|
|
27 |
})->average();
|
|
|
28 |
})->when(
|
|
|
29 |
$benchmarkables instanceof Closure,
|
|
|
30 |
fn ($c) => $c->first(),
|
|
|
31 |
fn ($c) => $c->all(),
|
|
|
32 |
);
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
/**
|
|
|
36 |
* Measure a callable or array of callables over the given number of iterations, then dump and die.
|
|
|
37 |
*
|
|
|
38 |
* @param \Closure|array $benchmarkables
|
|
|
39 |
* @param int $iterations
|
|
|
40 |
* @return never
|
|
|
41 |
*/
|
|
|
42 |
public static function dd(Closure|array $benchmarkables, int $iterations = 1): void
|
|
|
43 |
{
|
|
|
44 |
$result = collect(static::measure(Arr::wrap($benchmarkables), $iterations))
|
|
|
45 |
->map(fn ($average) => number_format($average, 3).'ms')
|
|
|
46 |
->when($benchmarkables instanceof Closure, fn ($c) => $c->first(), fn ($c) => $c->all());
|
|
|
47 |
|
|
|
48 |
dd($result);
|
|
|
49 |
}
|
|
|
50 |
}
|