hrtime
Returns the system's monotonic high resolution time in nanoseconds, for measuring elapsed time.
hrtime(bool $as_number = false): array|int|float|false- Added in PHP 7.3.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$as_numberoptional | bool= false | Return the time as a single number of nanoseconds instead of a [seconds, nanoseconds] array. |
Return value
array|int|float|falseBy default an array of two integers, [seconds, nanoseconds]. When as_number is true, the total nanoseconds as an int on 64-bit platforms or a float on 32-bit ones. Returns false on failure.
Errors
Does not throw. Returns false if the high resolution clock could not be read.
hrtime reads a monotonic clock: one that only ever moves forward and is never adjusted by NTP, a daylight saving change, or an administrator setting the system time. The value it returns counts from an arbitrary point with no meaning of its own, so a single reading is useless. Two readings subtracted are exact.
When to reach for it
Any time you want to know how long something took: profiling a query, timing a hot loop, adding a duration field to a log line, enforcing a timeout inside a retry loop. This is the one correct tool for that job in PHP. microtime and gettimeofday read the wall clock, and if NTP steps that clock mid-measurement your interval comes out wrong or negative.
Choosing a return form
Pass true for nearly everything — one 64-bit integer of nanoseconds subtracts cleanly with no floating-point error. Divide by 1e6 for milliseconds or 1e9 for seconds. The array form exists mainly for 32-bit builds, where the numeric form degrades to a float and starts losing precision.
Never format the value as a date. It is not a Unix timestamp and has no relationship to the epoch.
Example
When to use it
- Timing a database query or HTTP call and logging the duration in milliseconds
- Comparing two implementations of the same function in a micro-benchmark
- Enforcing a deadline inside a retry loop without being fooled by a clock adjustment
Frequently asked questions
What is the difference between hrtime and microtime?
hrtime reads a monotonic clock that never jumps, while microtime reads the wall clock that NTP can step forwards or backwards. Use hrtime for measuring durations and microtime only when you need an actual date-and-time value.
How do I convert hrtime to seconds or milliseconds?
hrtime(true) returns nanoseconds, so divide the difference of two readings by 1e6 for milliseconds or 1e9 for seconds. A single reading cannot be converted to a date — it is not a Unix timestamp.
Why does hrtime return a huge number?
It counts from an arbitrary origin, typically system boot, so the absolute value is meaningless and often runs to sixteen digits. Only the difference between two readings matters.
More examples
Comparing two implementations
Both branches produce the same sum, so the only difference measured is the cost of building an intermediate array. Exact figures vary by machine, but the ordering is consistent.
<?php
$data = range(1, 100000);
$t = hrtime(true);
$a = array_sum(array_map(fn($n) => $n * 2, $data));
$mapTime = hrtime(true) - $t;
$t = hrtime(true);
$b = 0;
foreach ($data as $n) { $b += $n * 2; }
$loopTime = hrtime(true) - $t;
printf("array_map: %.3f ms\nforeach: %.3f ms\n", $mapTime / 1e6, $loopTime / 1e6);
echo 'same result: ', var_export($a === $b, true), "\n";The array form and manual nanosecond maths
The array holds whole seconds and the leftover nanoseconds separately, so combining them means multiplying the seconds by a billion. hrtime(true) does this for you, which is why it is the usual choice.
<?php
$start = hrtime();
for ($i = 0; $i < 100000; $i++) { $x = $i ** 2; }
$end = hrtime();
$ns = ($end[0] - $start[0]) * 1_000_000_000 + ($end[1] - $start[1]);
echo 'start: [', $start[0], ', ', $start[1], "]\n";
printf("elapsed: %.3f ms\n", $ns / 1e6);
printf("matches numeric form? %s\n", var_export($ns > 0, true));A reusable timer
Wrapping the two readings in a helper keeps the measurement tight around the work. The helper returns milliseconds as a float, which is the unit most logs and dashboards expect.
<?php
function timeIt(callable $fn): array {
$t = hrtime(true);
$result = $fn();
return [$result, (hrtime(true) - $t) / 1e6];
}
[$value, $ms] = timeIt(fn() => array_sum(range(1, 500000)));
echo 'result: ', $value, "\n";
printf("took %.3f ms\n", $ms);
Discussion