Skip to content

Instantly share code, notes, and snippets.

@drealecs
Created October 20, 2023 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drealecs/c1a251f4e45f92994991687a99acb944 to your computer and use it in GitHub Desktop.
Save drealecs/c1a251f4e45f92994991687a99acb944 to your computer and use it in GitHub Desktop.
benchmark function that iterates multiple times through the callables received and benchmark their speed
<?php
function benchmark(callable ...$functions): void
{
$times = array_combine(array_keys($functions), array_fill(0, count($functions), 0.));
$baseTime = 0.;
$baseCallable = fn() => null;
$start = hrtime(true);
$count = 0;
while (hrtime(true) < $start + 1e9) {
$startCall = hrtime(true);
$baseCallable();
$baseTime += hrtime(true) - $startCall;
foreach ($functions as $key => $function) {
$startCall = hrtime(true);
$function();
$times[$key] += hrtime(true) - $startCall;
}
$count++;
}
foreach ($times as $key => $time) {
$times[$key] -= $baseTime;
}
if ($count < 100) {
echo "Methods too low. Iterated only {$count} times\n";
}
asort($times);
echo "Benchmark results after {$count} iterations in nanoseconds:\n";
foreach ($times as $key => $time) {
echo $key . ': ' . $time . "\n";
}
}
@drealecs
Copy link
Author

Usage example:

$x1 = 'A';

benchmark(
    a: fn() => (strtolower($x1) == 'a'),
    b: fn() => ($x1 == 'a' || $x1 == 'A'),
    c: fn() => in_array($x1, ['a', 'A']),
);

and example output:

Benchmark results after 2102631 iterations in nanoseconds:
c: 16409563
b: 31326178
a: 61903067

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment