Benchmark.php 1.9 KB

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