Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Benchmark.php

raw symbols SCIP
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 * Measure a callable or array of callables over the given number of iterations.
14 *
15 * @param \Closure|array $benchmarkables
16 * @param int $iterations
17 * @return array|float
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 * Measure a callable once and return the result and duration in milliseconds.
40 *
41 * @template TReturn of mixed
42 *
43 * @param (callable(): TReturn) $callback
44 * @return array{0: TReturn, 1: float}
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 * Measure a callable or array of callables over the given number of iterations, then dump and die.
59 *
60 * @param \Closure|array $benchmarkables
61 * @param int $iterations
62 * @return never
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 }