laurent
laurent

Reputation: 90776

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

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?

Upvotes: 12

Views: 2884

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 477060

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

Upvotes: 17

Paul Carroll
Paul Carroll

Reputation: 1887

No just calling once is fine. Use the seed value to make the random sequence the same on each execution. This could be useful in making (for example) a game's behaviour deterministic when you replay it for debugging.

Upvotes: 4

Dr McKay
Dr McKay

Reputation: 2568

Only once, at the start of your application.

Upvotes: 4

cprogrammer
cprogrammer

Reputation: 5675

call it once when the app starts

Upvotes: 3

Related Questions