In rand() considered harmful it is pointed out that srand(time(NULL))
is bad because srand
takes an unsigned int
, but for Microsoft's compiler, time_t
by default is a 64-bit number, therefore a narrowing conversion happens. However, time_t
is implementation-defined.
Since I see srand(time(NULL))
so prevalent (even on this site), should it be discouraged?
Any other value for the seed produces a different sequence. srand(time(NULL)); makes use of the computer's internal clock to control the choice of the seed. Since time is continually changing, the seed is forever changing.
The function srand () is used to provide seed for generating random numbers while rand () function generates the next random number in the sequence.
time(NULL) returns the number of seconds elapsed since 00:00:00 hours, GMT (Greenwich Mean Time), January 1, 1970.
srand() — Set Seed for rand() Function The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point.
Since I see srand(time(NULL)) so prevalent (even on this site), should it be discouraged?
It depends on how you want to use the output from from your generator (in this case, the output of rand()
).
If you only need a uniform distribution for single runs of your program, then srand(time(NULL))
is fine. This would be acceptable in a simulation where you only need a uniform distribution of numbers quickly.
If you want to submit a batch job so that multiple instances of your program run at the same time (and are effectively started at the same time), then srand(time(NULL))
will probably result in one or more instances producing the same random stream.
If you need a secure output, then you should not use srand(time(NULL))
because its often a Linear Congruential Generator (LCG). Joan Boyar taught us how to break them years ago. See Inferring sequences produced by a linear congruential generator missing low-order bits.
As for the problem with time_t
, just fold it to fit the argument expected by srand
if time_t
is too large. You might even fold in the process PID so that batch simulation jobs work as intended/expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With