How precise is Go's time, really?

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.


One of the problems with Python's time.time function is that it returns a float. A float is an IEEE 754 double-precision number which has 53 bits of precision.

Since it is now more than 2**30 seconds since 1970-01-01 (the epoch) you need 61 (31 + 30) bits of precision to store time accurate to the nanosecond since 1970-01-01.

Unfortunately that is 7 or 8 bits short of what you can store in a python float, meaning that python floats will always be less precise than go time.

To quantify that the demonstration below shows that python time is at most accurate to 100nS just due to the limitations of the float type.

>>> t = time()
>>> t
1359587524.591781
>>> t == t + 1E-6
False
>>> t == t + 1E-7
True

So go, starting with an int64 and counting in nS doesn't have these limitations and is limited to the precision of the underlying OS as explained very well by nemo.

Tags:

Time

Go