PHP Dates and Times
Generating a High-Precision Time
Problem
You need to measure time with finer than one-second resolution—for example, to generate a unique ID or benchmark a function call.Solution
Example Timing with microtime()$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
preg_match('/age=\d{1,5}/',$_SERVER['QUERY_STRING']);
}
$end = microtime(true);
$elapsed = $end - $start;
Discussion
Without an argument that evaluates to true, 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. This allows for more precision than can fit into a float, but makes it difficult to calculate with.
Since PHP 5.4.0, the $_SERVER superglobal array is populated with a REQUEST_TIME_FLOAT entry. This contains the time (including microseconds) when the request started. This makes it easy to determine how long a request has been running at any point—just compute microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'].
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 Generating an ID with microtime()
list($microseconds,$seconds) = explode(' ',microtime());
$id = $seconds.$microseconds.getmypid();
Note that the method in example 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() during the same microsecond.
No comments:
Post a Comment