PHP

Measure Code Block Execution Time

admin by @admin ADMIN
15m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Time a closure with microsecond precision and return both its result and the elapsed milliseconds. Great for quick perf experiments without pulling in a profiler.
PHP
Raw
<?php
function benchmark(callable $fn): array {
    $start  = hrtime(true);
    $result = $fn();
    $elapsedNs = hrtime(true) - $start;
    return [
        'result'  => $result,
        'ms'      => $elapsedNs / 1_000_000,
    ];
}

$bench = benchmark(function () {
    return array_sum(range(1, 1_000_000));
});
printf("Result: %d  took %.2f ms\n", $bench['result'], $bench['ms']);
// Result: 500000500000  took 12.34 ms
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.