Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeding rand() in C independently of time

Tags:

c

random

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?

like image 248
Rafael Avatar asked Jan 26 '26 17:01

Rafael


1 Answers

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

like image 181
nneonneo Avatar answered Jan 28 '26 07:01

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!