-
Notifications
You must be signed in to change notification settings - Fork 162
/
Benchmark.php
69 lines (57 loc) · 1.95 KB
/
Benchmark.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?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 (new Collection(Arr::wrap($benchmarkables)))->map(function ($callback) use ($iterations) {
return (new Collection(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 = (new Collection(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);
}
}