Question

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.

Was it helpful?

Solution

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:

#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
    timespec ts[100];

    for(auto &t : ts)
        clock_gettime(CLOCK_REALTIME, &t);
    timespec old_ts = {0};
    for(auto &t : ts)
    {
    long diff = 0;
    if (old_ts.tv_sec)
    {
        diff = t.tv_nsec - old_ts.tv_nsec;
    }
        cout << "ts.nsec: " << t.tv_nsec << " diff=" << diff << endl;
    old_ts = t;
    }
    return 0;
}

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:

#include <atomic>

typdef long long int id_type;
std::atomic<id_type> current_id;

id_type get_next_id()
{
   return current_id.fetch_add(1);
}

Not sure if visual studio has atomic, but you could use InterlockedINcrement64():

InterlockedIncrement64(&current); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top