My goal is to store timestamps in the range of nanoseconds. Let's say that I have two machines that needs to communicate, at precisely what time a task is done.
Let's just for the sake of the question, say that they a synchronized clocks.
Machine A stores its local time when it's done. Machine B transmits to A, at which time it is done. Machine A then calculates the difference.
My problem is, that the timedifference can actually be up to 60 seconds, but also down to .25ms. So I need to store the time in such a manner, that I can handle both, and calculate the timedifference.
Since time since epoch in nanoseconds is such a big number, I don't think I can store that in any variable that I know of.
How would you tackle this situation? My current though is, that I probably (somehow) could scale the time since epoch in ns down to the bits representing 1 minute, though I have no idea how to do that.
Hope you can help.
Best regards
Just use a 64-bit integer, signed (int64_t
) or unsigned (uint64_t
), and you'll be all fine.
The 64-bit space is really huge. It is not only enough to store time differences, but even to store absolute time values, which are usually measured as time passed since 1970-01-01 midnight.
For example, right now the number of seconds since 1970-01-01 is roughly:
1492432621.123456789
In nano-seconds, this is:
1492432621123456789
For comparison, the largest signed 64-bit integer value is:
9223372036854775807
This corresponds roughly to 2262-04-12, a date at which you almost certainly won't be alive anymore.
However, if you are still concerned by the possibility that your software runs for more than two centuries, won't be improved during that time, and will eventually crash, then you should either use unsigned 64-bit integers, which will give it some more centuries, or you should use 128-bit integers, which are almost certainly safe until the universe dies. Note that 128-bit integers are supported by all modern 64-bit architectures (__int128
or unsigned __int128
), so you can safely use them, unless, of course, you need to support legacy 32-bit systems. Or 16-bit systems. 8-bit, anyone?