Skip to content

Commit b4293d7

Browse files
committed
add benchmark utility class
1 parent 38dbbe8 commit b4293d7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/Illuminate/Support/Benchmark.php

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

0 commit comments

Comments
 (0)