15133

Imprecise numbers with microtime and floating point addition in PHP

Question:

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 <strong>123456789</strong> (representing a timestamp) and <strong>0.0987654321</strong> (representing microseconds), using the addition operator (<strong>+</strong>) 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.

<strong>Edit:</strong> 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 <strong>$start</strong> or <strong>$end</strong> 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.

Answer1:

Why don't you use <a href="http://de.php.net/manual/en/function.microtime.php" rel="nofollow">microtime(true)</a> which simply returns a microsecond timestamp as float? The parameter [bool] $get_as_float was added in PHP 5.0.0.

<strong>Regarding the comment about the "loss" of precision:</strong>

$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. <strong>This has nothing to do with the internal precision microtime(true) uses.</strong> You can always use <a href="http://de.php.net/manual/en/function.number-format.php" rel="nofollow">number_format()</a> or <a href="http://de.php.net/manual/en/function.sprintf.php" rel="nofollow">(s)printf()</a> to format the output to the precision you like.

Answer2:

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);

Answer3:

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

Recommend

  • Yii2: use error handler only for fatal errors or specify handled error types
  • Control key plus mouse wheel
  • Mouse up vs. touch up in Unity
  • How to Mantain Session with AngularJS Website from Native App?
  • SymfonyCMF RoutingBundle Doctrine PHPCR configuration error
  • Netlify fails to deploy site after public is added to .gitignore
  • Heroku Rails 4— FileNotFound jquery.ui.all
  • Add lots of data to SQLite Database in C#
  • How to get internal link from latest revision of a wikipedia page?
  • Convert certificate to byte array
  • Python mock a base class's attribute
  • Why $.each() is slower than for loop in jquery?
  • Python 3.7 Docker images
  • Error when deploying Tizen App - Failed to get a device information
  • Why does IntStream.range(0, 100000).parallel.foreach take longer then normal for loop
  • Upload synthesized speech from firebase function node.js server's tmp directory
  • wxPython UltimateListCtrl check (tick) listitem programatically
  • List using with references, changes behavior when used as a member
  • Nested AJAX Calls using .done
  • Is there a .NET method equivalent to NETWORKDAYS in Excel?
  • Was there ever a proposal to include the URL fragment into the HTTP request?
  • How to run Daphne Server (Django Channels) & workers in the background?
  • How does the dispatcher work when mixing sync/async with serial/concurrent queue?
  • Pick Out Specific Number from Array? [duplicate]
  • Splitting ReportLab table across PDF page (side by side)?
  • Create an Office365 mailbox from within C# Web API method
  • Request Access Token in Postman for Azure Function App protected by Azure AD B2C
  • Generate and export point cloud from Project Tango
  • Separating definition/instantiation of template classes without 'extern'
  • 'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs
  • Send array to next viewcontroller iOs xcode [duplicate]
  • Comma decimal separator is ignored by ASP.NET MVC model binder
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • Sql - ON DUPLICATE KEY UPDATE
  • How to use FirstOrDefault inside Include
  • PHP Permalinks.. how to change?
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • Access to a Matlab gui from the web