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?
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. :-)
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()
.
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());
rand
function. –
Normand 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.
t.tv_usec * t.tv_sec * pid
is a weak choice. That product is converted to an unsigned
when given to srand(unsigned)
. Each power-of-2 value of the 3, reduces the bits available for the seed. Instead use ^
: t.tv_usec ^ t.tv_sec ^ pid
. –
Earth 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())
.
© 2022 - 2024 — McMap. All rights reserved.
GetTickCount
. *nix has clock_gettime. – Dialectologystime(time(NULL) * getpid())
for instance, that would do the trick. – Putto