The best answer is to use <random>
. If you are using a pre C++11 version, you can look at the Boost random number stuff.
But if we are talking about rand()
and srand()
The best simplest way is just to use time()
:
int main()
{
srand(time(nullptr));
...
}
Be sure to do this at the beginning of your program, and not every time you call rand()
!
Side Note:
NOTE: There is a discussion in the comments below about this being insecure (which is true, but ultimately not relevant (read on)). So an alternative is to seed from the random device /dev/random
(or some other secure real(er) random number generator). BUT: Don't let this lull you into a false sense of security. This is rand()
we are using. Even if you seed it with a brilliantly generated seed it is still predictable (if you have any value you can predict the full sequence of next values). This is only useful for generating "pseudo"
random values.
If you want "secure" you should probably be using <random>
(Though I would do some more reading on a security informed site). See the answer below as a starting point: https://mcmap.net/q/65908/-recommended-way-to-initialize-srand for a better answer.
Secondary note: Using the random device actually solves the issues with starting multiple copies per second better than my original suggestion below (just not the security issue).
Back to the original story:
Every time you start up, time() will return a unique value (unless you start the application multiple times a second). In 32 bit systems, it will only repeat every 60 years or so.
I know you don't think time is unique enough but I find that hard to believe. But I have been known to be wrong.
If you are starting a lot of copies of your application simultaneously you could use a timer with a finer resolution. But then you run the risk of a shorter time period before the value repeats.
OK, so if you really think you are starting multiple applications a second.
Then use a finer grain on the timer.
int main()
{
struct timeval time;
gettimeofday(&time,NULL);
// microsecond has 1 000 000
// Assuming you did not need quite that accuracy
// Also do not assume the system clock has that accuracy.
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
// The trouble here is that the seed will repeat every
// 24 days or so.
// If you use 100 (rather than 1000) the seed repeats every 248 days.
// Do not make the MISTAKE of using just the tv_usec
// This will mean your seed repeats every second.
}
tv_usec
repeating is extremely low. Buttv_nsec
(withclock_gettime
) would be even better. – Mutatetv_sec
is going to repeat on two consecutive runs quite often, much more than 1000 times in 60 years, and if you wait any less, it's guaranteed to repeat a lot. It's also trivially predictable by an outside party, whereas predicting nanosecond-resolution clock values is essentially impossible. – Mutate