Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata