A lightweight benchmarking utility for measuring PHP callback execution time in milliseconds.
composer require --dev kenzal/php-benchmarkBenchmark can be used statically (recommended) or through an instance.
use Kenzal\Utility\Benchmark;
$result = Benchmark::mark(fn () => expensiveOperation(), 'operation-key');
$lastDuration = Benchmark::last('operation-key');
$averageDuration = Benchmark::avg('operation-key');
$history = Benchmark::history('operation-key');
Benchmark::clear('operation-key');use Kenzal\Utility\Benchmark;
$benchmark = new Benchmark();
$result = $benchmark->mark(fn () => expensiveOperation(), 'operation-key');
$lastDuration = $benchmark->last('operation-key');
$averageDuration = $benchmark->avg('operation-key');
$history = $benchmark->history('operation-key');
$benchmark->clear('operation-key');Each call to mark() stores a duration under the given key.
Benchmark::mark(fn () => usleep(1000), 'db');
Benchmark::mark(fn () => usleep(1500), 'db');
Benchmark::mark(fn () => usleep(500), 'api');
$dbHistory = Benchmark::history('db'); // [x, y]
$apiHistory = Benchmark::history('api'); // [z]
$all = Benchmark::history(['db', 'api']); // ['db' => [...], 'api' => [...]]If no key is provided, durations are stored using an internal default key and can still be read with:
Benchmark::history();
Benchmark::last();
Benchmark::avg();You can also average only the most recent entries for a key:
$avgLast10 = Benchmark::avg('db', 10);To reset history:
Benchmark::clear('db'); // clear a specific key
Benchmark::clear(); // clear the default key history
Benchmark::fresh(); // clear all keysmark(callable $callback, ?string $key = null, bool $dump = false): mixedlast(?string $key = null): ?floatavg(?string $key = null, ?int $last = null): ?floathistory(string|list<string>|null $key = null): arrayclear(?string $key = null): voidfresh(): void
Run the full project checks:
composer run testIf you're using Herd, run the Herd-specific pipeline:
composer run herd:test