kenzal/benchmark

A basic expression benchmarking utility

Maintainers

Package info

github.com/kenzal/php-benchmark

pkg:composer/kenzal/benchmark

Transparency log

Statistics

Installs: 19

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.1 2026-07-21 19:28 UTC

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.

Tests Code Style PHP Version Packagist Version License

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): mixed
  • last(?string $key = null): ?float
  • avg(?string $key = null, ?int $last = null): ?float
  • history(string|list<string>|null $key = null): array
  • clear(?string $key = null): void
  • fresh(): void

Development

Run the full project checks:

composer run test

If you're using Herd, run the Herd-specific pipeline:

composer run herd:test