What is the best way to seed srand()?

14,620

Solution 1

On POSIX systems, use clock_gettime to get the current time in nanoseconds. If you don't need a lot of bits, you can just forget the PRNG and use the low-order bits of the time as your random number directly. :-)

Solution 2

If *nix, Why don't you read directly from /dev/random?

Also you can gather noise from other devices, like the keyboard, mouse or the CPU temperature.

You can use an accelerometer and use it to gather noise from sea waves. The Wind also produce noise.

I believe Glib provides a function, g_random_int() which produces random numbers equally distributed in a fast and portable way.

Or you can just read the numbers of temporal files in /tmp and use that number to feed srand() with a time.h function, or read the content of one file in /tmp.

You can read each file from /usr/bin or / and gather some food for srand().

Solution 3

int pid ; // get it as per your OS
timeval t;
gettimeofday(&t, NULL);
srand(t.tv_usec * t.tv_sec * pid);

time gives you values based on second. gettimeofday is based on microseconds. So less chance of the same seed happening. Plus you are also using the process id.

Solution 4

Besides using time, another common way to seed your rand function is to use the process id of your program, since that is guaranteed to be unique.

The actual code is platform-dependent, but if you're on Windows, I believe you can use the function GetCurrentProcessId(), as in

srand(GetCurrentProcessId());
Share:
14,620
Matt
Author by

Matt

If I'm giving you a hard time, it's because I'm trying to learn as much as I can from you.

Updated on June 13, 2022

Comments

  • Matt
    Matt almost 2 years

    The way I learned was to initially seed the random number generator with srand(time(NULL)) and then use calls to rand() to generate random numbers. The problem with this approach is if I run my program multiple times in the same second, the random numbers generated will always be the same. What is a good way around this?