In PHP, microtime() returns the current Unix time with microsecond precision, as a string or a float.
By default it returns a string like '0.12345600 1700000000' (the fraction, a space, then the seconds). Pass true to get one float, which is the easiest way to time how long a piece of code takes.
Syntax
Call microtime() with the values you need. Start with this line.
PHP
$now = microtime(true);
Call
What it does
microtime()
Returns a string like "0.12345600 1700000000".
microtime(true)
Returns a float like 1700000000.123456.
microtime(true) - $start
Returns the seconds that passed since $start was taken.
The result changes on every call, so the examples below check the type and format instead of printing a raw time. For measuring code speed, hrtime(true) is even better because it cannot jump when the system clock changes.
Library declarations
PHP
microtime(bool $as_float = false): string|float
Parameters
Parameter
Description
as_float
Optional. If true, the time is returned as a float in seconds. If false (the default), a string in the form 'msec sec' is returned.
Return Value
Return Value
Description
string
When as_float is false: a string 'msec sec', where msec is the fraction of a second and sec is the seconds since the epoch.
float
When as_float is true: the Unix time as a float, with the fraction after the decimal point.
PHP Examples
Example 1 — Check the String Format
The default result is a string with two parts. A pattern check proves the format without printing a changing value.
microtime(true) before the loop saves the start time as a float.
The loop adds the numbers 1 to 100,000, which equals 5,000,050,000.
A second microtime(true) minus the start gives the elapsed seconds.
The elapsed time varies, so the example checks that it is not negative instead of printing it.
Frequently Asked Questions
By default a string like '0.12345600 1700000000'. With true it returns a float such as 1700000000.123456.
Save $start = microtime(true), run your code, then calculate microtime(true) - $start. The answer is in seconds.
time() returns whole seconds as an integer. microtime(true) adds the fraction of a second as a float.
hrtime() is better because it uses a monotonic clock that never goes backwards. microtime(true) is fine for quick, simple checks.
A float holds about 15 to 16 significant digits, so the microseconds at the end of a large timestamp can be rounded. Use hrtime(true) for exact nanoseconds.