A lightweight benchmark timer with laps and pause/unpause. This page is written for the PHP 8.1+ version (enum-backed state, private properties, getters).
Recommended: install via Composer and rely on autoloading.
composer require nsa-yoda/phpbenchtime
Start a timer, do some work, then end it and read the summary.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPBenchTime\Timer;
$t = new Timer();
$t->start('start');
usleep(120_000); // 120ms
$t->end();
print_r($t->summary());
Use lap() to split timing into segments. Each new lap automatically ends the previous lap.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPBenchTime\Timer;
$t = new Timer();
$t->start();
usleep(50_000);
$t->lap(); // lap 1 ends, lap 2 begins
usleep(75_000);
$t->lap(); // lap 2 ends, lap 3 begins
usleep(25_000);
$t->end(); // ends timer and ends the final lap
print_r($t->summary());
Pass a name to start() and lap() for more readable output.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPBenchTime\Timer;
$t = new Timer();
$t->start('boot');
usleep(40_000);
$t->lap('query db');
usleep(60_000);
$t->lap('render');
usleep(20_000);
$t->end();
print_r($t->summary());
Use pause() and unpause() to exclude time from the timer’s total. Paused time is tracked in paused.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPBenchTime\Timer;
$t = new Timer();
$t->start('work begins');
usleep(50_000);
$t->lap('before pause');
$t->pause();
usleep(200_000); // ignored by total (counted as paused)
$t->unpause();
usleep(50_000);
$t->lap('after pause');
$t->end();
print_r($t->summary());
end() while paused will finalize the pause automatically before stopping.
summary() returns an array. Values are floats in seconds (from microtime(true)).
Array
(
[running] => -1
[start] => 1706812345.1234
[end] => 1706812345.4567
[total] => 0.2333
[paused] => 0.2000
[laps] => Array
(
[0] => Array
(
[name] => boot
[start] => 1706812345.1234
[end] => 1706812345.2001
[total] => 0.0767
)
...
)
)
All internal state is private. Use getters to inspect it without mutating anything.
<?php
use PHPBenchTime\Timer;
use PHPBenchTime\TimerState;
$t = new Timer();
$t->start();
$state = $t->getState(); // TimerState enum
if ($state === TimerState::RUNNING) {
// ...
}
$start = $t->getStartTime(); // float
$end = $t->getEndTime(); // float
$paused = $t->getTotalPauseTime(); // float
$laps = $t->getLaps(); // array
$count = $t->getLapCount(); // int