Random Number Seed
Posted in Code
First dog watch, 2 bells (5:17 pm)

I have been running in to an error based on the ages-old method of seeding random generators with time(NULL), the number of seconds since the UNIX epoch. When this process runs in parallel with itself, the RNG gets the same seed because the time resolution isn't fine enough. There are other ways to seed based on hardware RNGs, reading from /dev/random or /dev/urandom, but I'm afraid I may call the function too often and deplete the entropy and make it less useful. Plus, cryptographic-level randomness is not one of my requirements. In talking with coworkers, we came up with adding the number of microseconds to the end of the UNIX timestamp to get a non-repeating number that will only get a duplicate seed during the same microsecond (i.e. highly unlikely).

Since the machine I'm poking around on doesn't have C++11, but does have Boost libraries, we came up with the following code:

#include 
...
int main(int argc, char **argv) {
...
    boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));

    boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

    boost::uint64_t x = (now - epoch).total_microseconds();
...

This function will work until we overflow the boost::uint64_t type (an unsigned long long), or roughly at 8:01:49 am on Wednesday January 19, 586524. After that it's someone else's problem.

6 Comments »

6 Responses to “Random Number Seed”

Leave a Reply