I am asking to see if there is a way of increasing the speed the srand(time(NULL));
function "refreshes"? I understand srand()
produces a new seed according to time (so once a second), but I am looking for an alternative to srand()
that can refresh more often than 1 second intervals.
When I run my program it produces the result it is supposed to, but the seed stays the same for essentially a second, so if the program is run multiple times a second the result stays the same.
Sorry for such a simple question, but I couldn't find an answer specifically for C anywhere online.
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 rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
Note: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.
The srand() function in C++ seeds the pseudo-random number generator used by the rand() function. It is defined in the cstdlib header file.
You could try fetching a seed value from some other source. On a unix system, for example, you could fetch a random four-byte value from /dev/random:
void randomize() {
uint32_t seed=0;
FILE *devrnd = fopen("/dev/random","r");
fread(&seed, 4, 1, devrnd);
fclose(devrnd);
srand(seed);
}
srand(time(NULL));
is not a function, it is rather two functions: time()
which returns the current time in seconds since the epoch; and srand()
which initialises the seed of the random number generator. You are initialising the seed of the rendom number generator to the current time in seconds, which is quite a reasonable thing to do.
However you have several misconceptions, you only actually need to run srand
once, or at most once every few minutes, after that rand()
will continue to generate more random numbers on its own, srand()
is just to set an initial seed for rand to start with.
Second, if you really do want to do this, while I don't see why you would you could use a function that returns the time to a higher precision. I would suggest gettimeofday()
for this purpose.
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