duanlang1196 2013-01-30 17:50
浏览 132
已采纳

实际上,Go的时间有多精确?

Go's time package claims giving a nanosecond precision. http://golang.org/src/pkg/time/time.go

I'm wondering how it is implemented and if I can trust it. My doubts come from Python, which clearly documents its difficulties and limitations with time:

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

Since the operating systems are giving such a hard time to python, how does Go achieve its nanosecond precision?

  • 写回答

2条回答 默认 最新

  • dtoqa66028 2013-01-30 18:41
    关注

    Well as for the implementation, time.Now() falls back to a function implemented in the runtime. You can review the C time implementation and the implementation for time·now in assembly (linux amd64 in this case). This then uses clock_gettime, which provides nano seconds resolution. On windows, this is realized by calling GetSystemTimeAsFileTime, which too generates nanoseconds (not as high res but nanoseconds).

    So yes, the resolution depends on the operating system and you can't expect it to be accurate on every OS but the developers are trying to make it as good as it can be. For example, in go1.0.3, time·now for FreeBSD used gettimeofday instead of clock_gettime, which only offers millisecond precision. You can see this by looking at the value stored in AX, as it is the syscall id. If you take a look at the referenced assembly, you can see that the ms value is mulitplied by 1000 to get the nanoseconds. However, this is fixed now.

    If you want to be sure, check the corresponding implementations in the runtime source code and ask the manuals of your operating system.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器