Skip to content

Commit

Permalink
add benchmark utility class
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Sep 23, 2022
1 parent 38dbbe8 commit b4293d7
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/Illuminate/Support/Benchmark.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Illuminate\Support;

use Closure;
use Illuminate\Support\Arr;

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 collect(Arr::wrap($benchmarkables))->map(function ($callback) use ($iterations) {
return collect(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 or array of callables over the given number of iterations, then die and dump.
*
* @param \Closure|array $benchmarkables
* @param int $iterations
* @return void
*/
public static function dd(Closure|array $benchmarkables, int $iterations = 1): void
{
dd(static::measure($benchmarkables, $iterations));
}
}

1 comment on commit b4293d7

@MrMohamedAbdallah
Copy link

@MrMohamedAbdallah MrMohamedAbdallah commented on b4293d7 Oct 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be useful to have a syntax like that to spot the bottleneck.

Benchmark::start("label_1");
// Some code
Benchmark::end("label_1");

Benchmark::start("label_2");
// Some code
Benchmark::end("label_2");

Benchmark::dd();

I can work on that.

Please sign in to comment.