Skip to content
Tutorials Center
My learning

Topics

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
<?php
$start = hrtime(true);
usleep(1000);
$ms = (hrtime(true) - $start) / 1_000_000;

Try it

PHP Types and measuring elapsed time

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.

PHP A small benchmark helper

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

PHP
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), unlike microtime(true) or time().
  • The string form is awkward. microtime() without true returns text; parse it only for old code. Prefer microtime(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: DateTimeImmutable formats microseconds with u, and date() cannot.
  • Absolute meaning only for microtime. The value of hrtime() 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(); use random_int() or uniqid() with care.
  • Built-in profiling: memory_get_peak_usage() complements timing.