Rafael
Rafael

Reputation: 153

Seeding rand() in C independently of time

I am using stdlib to generate random numbers. I know there are better generators but stdlib is quite enough for me.

I am doing:

while(condition){
    sleep(1);
    srand(time(NULL));
    r=rand();
}

It is inside a loop so I need sleep(1) or the seed is the same and the number is repeated. The fact is that I need to generate thousands or maybe millions of numbers and if I wait 1 second per number it will take a long time. So there is another way independently of time to seed?

Upvotes: 3

Views: 124

Answers (1)

nneonneo
nneonneo

Reputation: 179422

You only need to seed once (at startup), then generate as many numbers as you like. Don't reseed once per number - it's pointless, and you'd basically have to generate random seeds to generate random numbers (which rather defeats the purpose of using a PRNG in the first place).

Upvotes: 11

Related Questions