• Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Precios
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

156
Vistas
Is it possible to increase the refresh speed of srand(time(NULL)) in C?

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.

11 months ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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);
}
11 months ago · Santiago Trujillo Denunciar

0

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.

11 months ago · Santiago Trujillo Denunciar

0

Under Windows you can use GetTickCount() instead of time(). It changes on 50ms interval (if remember correctly).

11 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.