Php time () and microtime () sometimes do not match

When registering some data with microtime () (using PHP 5), I came across some values ​​that are slightly out of phase with respect to the timestamp of my log file, so I just tried to compare the output of time () and microtime () with a simple script (you can simply compress it here to limit data output):

<?php for($i = 0; $i < 500; $i++) { $microtime = microtime(); $time = time(); list($usec, $sec) = explode(" ", $microtime); if ((int)$sec > $time) { echo $time . ' : ' . $microtime . '<br>'; } usleep(50000); } ?> 

Now that $ microtime is declared before $ time, I expect it to be smaller and nothing should be output; however, this is obviously not the case, and from time to time, $ time is less than the seconds returned from microtime (), as in this example the (truncated) output:

 1344536674 : 0.15545100 1344536675 1344536675 : 0.15553900 1344536676 1344536676 : 0.15961000 1344536677 1344536677 : 0.16758900 1344536678 

Now this is just a small gap; however, I have seen some series where the difference is (pretty) more than a second ... so how is this possible?

+4
source share
2 answers

If you look at the time and microtime , you see that they are radically different:

Since the C time call is accurate to only a second, it can also deliberately use a low-precision time source.

In addition, on modern x86_64 systems, both C functions can be implemented without a system call by looking at specific processor registers . If you use a multi-core system, these registers may not match exactly on the cores, and this may be the reason.

Another potential reason for the discrepancy is that NTPd (a temporary daemon) or some other user-space process changes the clock. Usually such effects should be avoided adjtime .

All these considerations are quite esoteric. To further debug the problem, you should:

  • Define OS and CPU architecture (tooltip: let us know!)
  • Try to force the process on one core .
  • Stop all programs that (or may be) adjust the system time.
+5
source

This may be due to the fact that microtime () uses floating point numbers, and therefore rounding errors may occur .

You can specify the precision of floating point numbers in php.ini

0
source

All Articles