I need a 'good' way to initialize the pseudo-random number generator in C++. I've found an article that states:
In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header ctime) is different each second, which is distinctive enough for most randoming needs.
Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts.
I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from /dev/urandom
.
Thanks!
EDIT
Yes, I am actually starting my application multiple times a second and I've run into collisions.
On windows:
provides a better seed than
time()
since its in milliseconds.Suppose you have a function with a signature like:
An excellent source of entropy for a random seed is a hash of the following:
clock_gettime
(seconds and nanoseconds) without throwing away the low bits - they're the most valuable.p
, cast touintptr_t
.p
, cast touintptr_t
.At least the third, and possibly also the second, derive entropy from the system's ASLR, if available (the initial stack address, and thus current stack address, is somewhat random).
I would also avoid using
rand
/srand
entirely, both for the sake of not touching global state, and so you can have more control over the PRNG that's used. But the above procedure is a good (and fairly portable) way to get some decent entropy without a lot of work, regardless of what PRNG you use.