3.13. Generating a High-Precision Time
Problem
You need to measure time with finer than one-second resolution, for example to generate a unique ID.
Solution
Use microtime( )
:
list($microseconds,$seconds) = explode(' ',microtime());
Discussion
The function microtime( )
returns a string that
contains the microseconds part of elapsed time since the epoch, a space,
and seconds since the epoch. For example, a return value of
0.41644100 1026683258
means that
1026683258.41644100 seconds have elapsed since the epoch. A string is
returned instead of a double because the double
doesn’t have enough capacity to hold the entire
value with microsecond precision.
Time including microseconds is useful for generating unique IDs. When combined with the current process ID, it guarantees a unique ID, as long as a process doesn’t generate more than one ID per microsecond:
list($microseconds,$seconds) = explode(' ',microtime()); $id = $seconds.$microseconds.getmypid();
However, this method is not as foolproof on
multithreaded systems, where there is a nonzero (but very tiny)
chance that two threads of the same process could call
microtime( )
simultaneously.
See Also
Documentation on microtime( )
at
http://www.php.net/microtime.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.