view raw
Matteo Monti Matteo Monti - 7 months ago 60
C++ Question

Portable good precision double timestamp in C++?

Here's what I'd need to do:

double now=getdoubletimestampsomehow();

Where getdoubletimestampsomehow() should be a straight-forward, easy to use function returning a double value representing the number of seconds elapsed from a given date. I'd need it to be quite precise, but I don't really need it to be more precise than a few milliseconds. Portability is quite important, if it isn't possible to directly port it anywhere could you please tell me both an unix and a windows way to do it?


Portable good precision double timestamp in C++?

There is no portable way to get high-precision timestamp (milliseconds) without using 3rd party libraries. Maximum precision you'll get is 1 second, using time/localtime/gmtime.

If you're fine with 3rd party libraries, use either Boost or Qt 4.

both an unix and a windows way to do it?

GetSystemTime on Windows and gettimeofday on linux.

Please note that if you're planning to use timestamps to determine order of some events, then it might be a bad idea. System clock might have very limited precision (10 milliseconds on windows platform), in which case several operations performed consequently can produce same timestamp. So, to determine order of events you would need "logical timestamps" ("vector clock" is one of examples).

On windows platform, there are highly precise functions that can be used to determine how much time has passed since some point in the past (QueryPerformanceCounter), but they aren't connected to timestamps.