9

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?

Matt
  • 21,026
  • 18
  • 63
  • 115

5 Answers5

6

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. :-)

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • I'm guessing somebody didn't like my idea of using the low bits of the current time for RNG. However, given the factors that affect them (memory latency, cache hits/misses, TLB misses, swapping, interrupt timing, scheduling, ...) and the fact that nanoseconds correspond roughly to cycles on modern machines, they're a pretty damn good entropy source. – R.. GitHub STOP HELPING ICE Apr 11 '13 at 23:30
  • I concur. It is both clever and elegant. Hence my question. I looked puzzled at the downvote for such appropriate answer to issue at hand. It pretty much solves the question (running the program multiple times in the same second and getting the same result each time). – Jean Apr 11 '13 at 23:36
2
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.

user93353
  • 13,733
  • 8
  • 60
  • 122
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().

yeyo
  • 2,954
  • 2
  • 29
  • 40
1

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());
Parker Kemp
  • 719
  • 1
  • 10
  • 23
-2

Beside inputting the time, you could add the CPU time to this, which I believe can be do with clock(). So it would look like this: srand(time() + clock()).

fibonatic
  • 216
  • 1
  • 12