kenzal / benchmark
A basic expression benchmarking utility
v1.0.1
2026-07-21 19:28 UTC
Requires
- php: ^8.1
Requires (Dev)
This package is auto-updated.
Last update: 2026-07-21 19:42:06 UTC
README
A lightweight benchmarking utility for measuring PHP callback execution time in milliseconds.
Installation
composer require --dev kenzal/php-benchmark
Usage
Benchmark can be used statically (recommended) or through an instance.
Static usage
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');
Instance usage
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');
Working with keys and history
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 keys
API
mark(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
Development
Run the full project checks:
composer run test
If you're using Herd, run the Herd-specific pipeline:
composer run herd:test