start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

3.14. Generating a High-Precision Time

3.14.1. Problem

You need to measure time with finer than one-second resolution, for example to generate a unique ID.

3.14.2. Solution

Use microtime( ) :

list($microseconds,$seconds) = explode(' ',microtime());

3.14.3. 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.

3.14.4. See Also

Documentation on microtime( ) at http://www.php.net/microtime.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.