views:

716

answers:

3

I'm having a terrible time convincing myself what I've done here is a good idea. The specific section I find objectionable is:

return ((float)($now+$sec).'.'.$mic);

In order to preserve the floating point precision, I'm forced to either fall back on the BC or GMP libraries (neither of which is always available). In this case, I've resorted to jamming the numbers together with string concatenation.

<?php

// return the current time, with microseconds
function tick() {
    list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
    return ((float)($now+$sec).'.'.$mic);
}

// compare the two given times and return the difference
function elapsed($start, $end) {
    $diff = $end-$start;

    // the difference was negligible
    if($diff < 0.0001)
     return 0.0;

    return $diff;
}

// get our start time
$start = tick();

// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);

// get our end time
$end = tick();

$elapsed = elapsed($start, $end);

// should produce output similar to: float(2.00113797188)
var_dump($elapsed);

?>

If I attempt to add two numbers like 123456789 (representing a timestamp) and 0.0987654321 (representing microseconds), using the addition operator (+) I invariably end up with 123456789.099. Even when casting the integer to float, the result is the same.

Is there a solution for this issue which is 1) not a hack and 2) doesn't involve string concatenation? I shouldn't have to fall back on this sort of garbled code in order to get an accurate timestamp with microsecond resolution.

Edit: As S. Gehrig has explained, floating point numbers in PHP can be, at times, a bit tricky to display. The "precision" indicated in the PHP configuration is regarding display. The actual values are not rounded like I thought. A far simpler solution to the above code would look like so:

// return the current time, with microseconds
function tick() {
    return microtime(true);
}

// compare the two given times and return the difference
function elapsed($start, $end) {
    return $end-$start;
}

// get our start time
$start = tick();

// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);

// get our end time
$end = tick();

$elapsed = elapsed($start, $end);

// should produce output similar to: float(2.00113797188)
var_dump($elapsed);

If you were to examine $start or $end before subtracting one from the other, it might appear they were rounded to the hundredths position. This is not the case. It seems arbitrary precision is maintained for arithmetic while the display is limited.

+2  A: 

Why don't you use microtime(true) which simply returns a microsecond timestamp as float? The parameter [bool] $get_as_float was added in PHP 5.0.0.

Regarding the comment about the "loss" of precision:

$start = microtime(true);
$end = microtime(true);
echo $end - $start;
// prints 7.1526861190796

microtime(true) is not limited to 2 decimal places. What the poster encounters is the effect of the configuration setting precision which controls how many decimal places will be printed when outputting float variables. This has nothing to do with the internal precision microtime(true) uses. You can always use number_format() or (s)printf() to format the output to the precision you like.

Stefan Gehrig
I would, but the precision is rounding to 2 places and there doesn't seem to be a way to change this. By default, PHP's precision is 12 places... yet this function doesn't honor that. Check it with: php -r 'echo microtime(true);'I have no idea what causes it to round like that.
spligak
The precision of 12 decimal places for float INCLUDES the decimals before the comma - so 12 places precision is exactly what you're seeing.
Michael Borgwardt
This is just a display issue and is controlled by the configuration setting `precision`: http://us2.php.net/manual/en/ini.core.php#ini.precision. Internally a float has a precision of roughly 14 decimal digits.
Stefan Gehrig
I was referring to the value of 123456789.099 cited in the question - that's 12 places
Michael Borgwardt
A: 

Floating point types are inherently imprecise. Either live with it, or don't use them.

Michael Borgwardt
Ultimatum noted. I suppose I'll "live with it."
spligak
BC, GMP or strings represent the alternative "don't use them".
Michael Borgwardt
You can use floating-point, but decide not to live with quite so much imprecision.http://en.wikipedia.org/wiki/Kahan_summation_algorithm
Robert L
A: 

First, spligak, I see that your code contains an error.

list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
return ((float)($now+$sec).'.'.$mic);

If $mic has fewer than six digits, you get garbage results. Do a desk check on

the case where microtime() returns "0.000009 1234567890"

Second, you can greatly reduce the floating-point error as follows: (WARNING: untested code!)

// compare the two given times and return the difference

// get our start time
$start = microtime();

// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);

// get our end time
$end = microtime();

// work around limited precision math
// subtract whole numbers from whole numbers and fractions from fractions

list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
$elapsed = ((float)$end_usec)-((float)$start_usec);
$elapsed += ((float)$end_sec)-((float)$start_sec);

// please check the output
var_dump($elapsed);
Robert L