Is it possible to increase the update rate of srand (time (NULL)) in C?

I am asking if there is a way to increase the speed the function is srand(time(NULL));

"updated"? I understand that it srand()

creates a new seed based on time (so once per second), but I am looking for an alternative srand()

that can refresh more often than 1 second intervals.

When I run my program, it produces a result that should be used, but the seed remains essentially the same for a second, so if the program is run multiple times per second, the result remains the same.

Sorry for such a simple question, but I couldn't find an answer specifically for C anywhere online.

+3


source to share


3 answers


srand(time(NULL));

is not a function, it is rather two functions: time()

that returns the current time in seconds since the epoch; and srand()

, which initializes the seed of the random number generator. You are initializing the seeds of the rendom number generator at the current time in seconds, which is perfectly reasonable to do.

However, you have a few misconceptions, you just need to run srand

once or not more often than once every few minutes, after which it rand()

will continue to generate more random numbers on its own srand()

- this is just set the seed to start rand.



Second, if you really want to do this, I don't understand why you could use a function that returns the time to a higher precision. I would suggest gettimeofday()

for this purpose.

+3


source


You can try to get the initial value from another source. For example, on a unix system, you can get a random 4 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);
}

      

+3


source


On Windows, you can use GetTickCount()

instead time()

. It changes with an interval of 50 ms (if you remember it correctly).

+3


source







All Articles