php time() and microtime() do sometimes not concord

前端 未结 2 876
旧巷少年郎
旧巷少年郎 2021-01-05 18:25

While logging some data using microtime() (using PHP 5), I encountered some values that seemed slightly out of phase in respect to the timestamp of my log file, so I just tr

相关标签:
2条回答
  • 2021-01-05 19:00

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

    You can specify floating point numbers' precision in php.ini

    0 讨论(0)
  • 2021-01-05 19:03

    If you look at the implementations of time and microtime, you see they're radically different:

    • time just calls the C time function.
    • microtime has two implementations: If the C function gettimeofday is available (which it should be on a Linux system), it is called straight-forward. Otherwise they pull of some acrobatics to use rusage to calculate the time.

    Since the C time call is only precise up to a second, it may also intentionally use a low-fidelity time source.

    Furthermore, on modern x86_64 systems, both C functions can be implemented without a system call by looking into certain CPU registers. If you're on a multi-core system, these registers may not exactly match across cores, and that could be a reason.

    Another potential reason for the discrepancies is that NTPd(a time-keeping daemon) or some other user-space process is changing the clock. Normally, these kinds of effects should be avoided by adjtime.

    All of these rationales are pretty esoteric. To further debug the problem, you should:

    • Determine OS and CPU architecture (hint: and tell us!)
    • Try to force the process on one core
    • Stop any programs that are (or may be) adjusting the system time.
    0 讨论(0)
提交回复
热议问题