time - Go 的时间到底有多精确?

标签 time go

Go 的时间包声称可以提供纳秒级的精度。 http://golang.org/src/pkg/time/time.go

我想知道它是如何实现的,我是否可以信任它。我的疑虑来自 Python,它清楚地记录了它的困难和限制:

From http://docs.python.org/2/library/time.html

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

On the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating point numbers, time() returns the most accurate time available (using Unix gettimeofday() where available), and sleep() will accept a time with a nonzero fraction (Unix select() is used to implement this, where available).

既然操作系统对 python 的要求如此之高,那么 Go 是如何实现其纳秒级精度的呢?

最佳答案

关于实现,time.Now() 回退到运行时中实现的函数。 您可以查看 C time implementation以及 time·now in assembly 的实现(在这种情况下是 linux amd64)。然后使用 clock_gettime ,它提供纳秒分辨率。在 Windows 上,这是通过调用 GetSystemTimeAsFileTime 来实现的,too generates nanoseconds (不是高分辨率,而是纳秒)。

所以是的,分辨率取决于操作系统,您不能指望它在每个操作系统上都是准确的,但开发人员正在努力使其尽可能好。例如,在 go1.0.3 中,time·now for FreeBSD used gettimeofday而不是 clock_gettime,它只提供毫秒精度。您可以通过查看存储在 AX 中的值来了解这一点,因为它是 syscall id .如果您查看引用的程序集,您可以看到 ms 值乘以 1000 以获得纳秒。但是,这是固定的 now .

如果您想确定,请查看运行时源代码中的相应实现,并询问您的操作系统的手册。

关于time - Go 的时间到底有多精确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610459/

相关文章:

go - golang代码是否有一个既定的模式名称,看起来类似于mixin

go - 获取/文章/:article_id Not working Gin-Gonic/Gin

java - 将 Joda-Time DateTime 格式化为字符串

javascript - 当输入类型日期和输入类型时间使用相同的ng-model时,如何清除仅日期或仅时间?

azure - Azure 上的全局化和文化设置

pointers - 戈朗 : Passing in Slice as Reference issue

go - Go中的结构队列

python - 如何获取过去7小时的strftime?

javascript - 使用 setTimeout 与比较更新循环上的时间戳

go - gorilla/rpc JSON RPC 服务没有响应