PHP code example of philiprehberger / php-stopwatch
1. Go to this page and download the library: Download philiprehberger/php-stopwatch library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Fire a callback when measurement exceeds a threshold
$result = Stopwatch::measureWithThreshold(
callback: function () {
processLargeDataset();
},
thresholdMs: 500.0,
onExceeded: function (MeasureResult $result) {
Log::warning("Slow operation: {$result->durationFormatted}");
},
);
// Register thresholds on a running stopwatch
$sw = Stopwatch::start();
$sw->onThreshold(1000.0, function (StopwatchResult $result) {
alert("Operation exceeded 1 second: {$result->durationFormatted}");
});
$sw->onThreshold(5000.0, function (StopwatchResult $result) {
alert("Critical: operation exceeded 5 seconds!");
});
doWork();
$result = $sw->stop(); // Callbacks fire here if thresholds exceeded
$report = Stopwatch::compare([
'array_map' => fn () => array_map(fn ($x) => $x * 2, range(1, 1000)),
'foreach' => fn () => array_walk($arr = range(1, 1000), fn (&$x) => $x *= 2),
], iterations: 100);
echo $report->toTable();
// | Name | Mean | Median | Δ vs Best |
// |-----------|---------|---------|------------|
// | array_map | 0.12ms | 0.11ms | baseline |
// | foreach | 0.18ms | 0.17ms | +50.00% |
$report->fastest(); // BenchmarkEntry with lowest mean
$report->slowest(); // BenchmarkEntry with highest mean
$report->rankings(); // Sorted by mean ascending
$proxy = Stopwatch::profile($myService);
// Use the proxy like the original object — all calls are timed
$proxy->fetchUsers();
$proxy->fetchUsers();
$proxy->processData($input);
$profile = Stopwatch::getProfile($proxy);
// ['fetchUsers' => StopwatchStats, 'processData' => StopwatchStats]
foreach ($profile as $method => $stats) {
echo "{$method}: mean={$stats->mean()}ms, calls={$stats->min()}..{$stats->max()}ms\n";
}
$original = $proxy->getTarget(); // Access the wrapped object
$sw = Stopwatch::start();
$sw->lap('step-1');
$sw->lap('step-2');
$sw->lap('step-3');
$result = $sw->stop();
$stats = $result->stats();
echo $stats->mean(); // Mean lap duration in ms
echo $stats->median(); // Median lap duration in ms
echo $stats->p95(); // 95th percentile
echo $stats->standardDeviation(); // Standard deviation
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.