To generate global unique ids, I need something like a timestamp of their creation. But those ids can be generate directly after each other in source code. So the time with milliseconds isn't accurate enough and could unintentionally produce equal ids.
Thefore I need a timestamp exact enough that it differs every time it is fetched. I though about CPU cycles, but I don't know if there is a way to get this information.
Since this is for a realtime game, fetching the timestamp is performance related. Moreover, it is cross-plattform compatible to Linux, Windows and Mac, so of course the timestamp should be, too. If there is no standard way, I could live with three distinctive solutions for the systems.
Timestamps are not very good for this, unless you are guaranteed to have a high resolution time-source. Some systems have this, others don't.
In particular, if the system has multiple CPU's, the "timestamp counter" for each CPU may not be in sync, so you may get duplicates simply because the number of clockcycles on one CPU is "behind" the number of clockcycles on another CPU.
In a POSIX system, you may be able to use a
clock_gettime
which does have a nanosecond resolution, and should be fairly fast too.I wrote this code to test it out:
Edit:
Of course, the absolutely simplest form of a unique ID is a 64-bit atomic counter - it is the fastest, and it's simple. Assuming you have C++11 features:
Not sure if visual studio has atomic, but you could use
InterlockedINcrement64()
: