Skip to content

Instantly share code, notes, and snippets.

@thedava
Created October 21, 2020 17:06
Show Gist options
  • Save thedava/fae59f51c5eadd7865d532f8295df206 to your computer and use it in GitHub Desktop.
Save thedava/fae59f51c5eadd7865d532f8295df206 to your computer and use it in GitHub Desktop.
Extremely simple php benchmark
<?php
$benchMark = new class() {
const MEASUREMENT_BLOCKS = 20;
const ITERATIONS = 100000;
private function variant1(): void
{
// Implement variant 1 here
}
private function variant2(): void
{
// Implement variant 2 here
}
private function executeVariant(callable $variant): float
{
$total = 0;
for ($runs = 0; $runs < self::MEASUREMENT_BLOCKS; $runs++) {
$startTime = microtime(true);
for ($i = 0; $i < self::ITERATIONS; $i++) {
call_user_func_array($variant, []);
}
$endTime = microtime(true);
$total += abs($startTime - $endTime);
}
return $total / self::MEASUREMENT_BLOCKS;
}
public function run(): void
{
echo 'Begin BenchMark...', PHP_EOL;
$variant1 = 0.0;
$variant2 = 0.0;
$start = microtime(true);
// First block (1, 2)
echo ' First Execution', PHP_EOL;
echo ' Variant 1', PHP_EOL;
$variant1 += $this->executeVariant([$this, 'variant1']);
echo ' Variant 2', PHP_EOL;
$variant2 += $this->executeVariant([$this, 'variant2']);
echo PHP_EOL;
// Second block (2, 1)
echo ' Second Execution', PHP_EOL;
echo ' Variant 2', PHP_EOL;
$variant2 += $this->executeVariant([$this, 'variant2']);
echo ' Variant 1', PHP_EOL;
$variant1 += $this->executeVariant([$this, 'variant1']);
echo PHP_EOL;
$totalDuration = microtime(true) - $start;
echo 'Variant 1: ', sprintf('%.4f Seconds', $variant1 / 2), PHP_EOL;
echo 'Variant 2: ', sprintf('%.4f Seconds', $variant2 / 2), PHP_EOL;
echo PHP_EOL;
echo 'Total runs: ', (self::MEASUREMENT_BLOCKS * self::ITERATIONS * 2) * 2;
echo ' (', (self::MEASUREMENT_BLOCKS * self::ITERATIONS * 2), ' per variant)', PHP_EOL;
echo 'Total duration: ', sprintf('%.4f Seconds', $totalDuration), PHP_EOL;
}
};
$benchMark->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment