Recipe 3.13. Generating a High-Precision Time


3.13.1. Problem

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

3.13.2. Solution

Use microtime(true) to get the current time in seconds and microseconds. Example 3-37 uses microtime(true) to time how long it takes to do 1,000 regular expression matches.

Timing with microtime( )

<?php $start = microtime(true); for ($i = 0; $i < 1000; $i++) {     preg_match('/age=\d+/',$_SERVER['QUERY_STRING']); } $end = microtime(true); $elapsed = $end - $start;

3.13.3. Discussion

Support for the optional argument microtime( ) was added in PHP 5.0.0. Without that argument, with an argument that doesn't evaluate to true, or in an earlier version of PHP, 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.

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. Example 3-38 uses microtime( ) (with its string return format) to generate just such an ID.

Generating an ID with microtime( )

<?php [list($microseconds,$seconds) = explode(' ',microtime()); $id = $seconds.$microseconds.getmypid(); ?>

Note that the method in Example 3-38 is not as foolproof on multithreaded systems, where there is a non-zero (but very tiny) chance that two threads of the same process could call microtime( ) during the same microsecond.

3.13.4. See Also

Documentation on microtime( ) at http://www.php.net/microtime. The uniqid( ) function is good for generating unique IDs.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net