PHP Reference ยท Date and Time
PHP microtime() and hrtime() functions
Reference for PHP microtime() and hrtime(): get microsecond timestamps, measure elapsed time with a monotonic clock and benchmark code correctly.
microtime() returns the current Unix time with microsecond precision, and hrtime() returns a high-resolution monotonic counter in nanoseconds. Both are meant for measuring how long something takes, but they are not the same clock.
microtime(true) is a wall-clock time: it is a float such as 1751328000.123456 and follows the system clock, which can be adjusted. hrtime() is a counter that only moves forward and is not related to calendar time, which makes it the right tool for benchmarks (PHP 7.3 and later).
<?php $start = hrtime(true); usleep(1000); $ms = (hrtime(true) - $start) / 1_000_000;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
microtime(bool $as_float = false): string|float hrtime(bool $as_number = false): array|int|float|false
| Name | Description |
|---|---|
$as_float |
false returns a string "msec sec" (a fraction, a space, whole seconds); true returns a float of seconds since the epoch. |
$as_number |
false returns [seconds, nanoseconds]; true returns one integer of nanoseconds (on 64-bit builds, an int; otherwise a float). |
Return value: as in the table. hrtime() can return false only on systems without a monotonic clock, which is very rare.
Usage notes
- Use
hrtime(true)for durations. It is not affected by clock adjustments (NTP, manual changes), unlikemicrotime(true)ortime(). - The string form is awkward.
microtime()withouttruereturns text; parse it only for old code. Prefermicrotime(true). - Float precision. A timestamp around 1.7 billion seconds in a double leaves roughly microsecond resolution; do not expect more.
- Readable timestamps with fractions:
DateTimeImmutableformats microseconds withu, anddate()cannot. - Absolute meaning only for
microtime. The value ofhrtime()has an arbitrary starting point; subtracting two readings is the only valid use. - Benchmarking tips: repeat the work, take the minimum or median, warm up first, and measure outside any I/O. A single run is mostly noise.
- Do not seed or ID things with
microtime(); userandom_int()oruniqid()with care. - Built-in profiling:
memory_get_peak_usage()complements timing.