Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is srand(time(NULL)) bad?

Tags:

c++

random

srand

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?

like image 995
user4111372 Avatar asked Oct 05 '14 20:10

user4111372


People also ask

What is the use of srand time NULL C?

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.

What is the purpose of using srand() function as in below code srand time null));?

The function srand () is used to provide seed for generating random numbers while rand () function generates the next random number in the sequence.

What does time NULL return?

time(NULL) returns the number of seconds elapsed since 00:00:00 hours, GMT (Greenwich Mean Time), January 1, 1970.

What is srand?

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.


1 Answers

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.

like image 166
jww Avatar answered Sep 22 '22 19:09

jww