Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often should I call srand() in a C++ application?

Tags:

c++

random

srand

I have a C++ application which calls rand() in various places. Do I need to initialize srand() regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?

like image 412
laurent Avatar asked Aug 05 '11 09:08

laurent


People also ask

How often do you Srand?

Only once, at the start of your application. Save this answer.

What happens if you call Srand multiple times?

srand seeds the pseudorandom number generator. If you call it more than once, you will reseed the RNG. And if you call it with the same argument, it will restart the same sequence.

Why do you need Srand () when getting a random number?

The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.

Should Srand be in Main?

In general, libraries should never call srand . The call to srand should be made once, usually in main , and is the responsibility of the application. Any other solution ends up with multiple libraries competing with each other.


1 Answers

If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand at all, but rather something threadsafe like drand48_r, which lets you maintain a per-thread state (so you can seed once per thread).

like image 74
Kerrek SB Avatar answered Sep 18 '22 04:09

Kerrek SB