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(¤t);