Hello I want to have a code which gives a random value faster than a value per second.
Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

	int main()
{
	int x;
	srand(time(NULL));
	x = rand()%100 +1;
	printf("%d", x);
	return 0;
}

Can you please tell me how can I make it quicker?

Edited 6 Years Ago by newbiecoder: n/a

What makes you believe that rand() only produces one random value per second? Have you profiled it? What is the speed of your computer? A computer with a faster CPU will process code faster. I wrote a little program that generated 1,000,000 randm numbers on 43 millisonds and if I add the mod operator like you posted it generates them in 62 milliseconds.

If you are looking to speed up a program then look elsewhere.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main()
{
    time_t t1, t2;
    srand((unsigned int)time(0));
    t1 = clock();
    for(size_t i = 0; i < 1000000; i++)
        rand();
    t2 = clock();
    printf("time %u\n", t2 - t1 );

}

Edited 6 Years Ago by Ancient Dragon: n/a

I am actually not sure that it produces per second, but I guessed so because when I execute this code multiple times a second it gives same result, how can I make it give different results faster without using a faster CPU?

You are using time() as the seed to srand(). Call srand() only once during the lifetime of the program, not every time you call rand(). Put the call to srand() near the beginning of main() and you will see different results every time rand() is called.

Edited 6 Years Ago by Ancient Dragon: n/a

I changed my code to this type , did i do the correct thing? It still gives same results, is there any other thing to seed srand() to make rand() faster?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

	int main()
{
	srand(time(NULL));
	float x, low_number, high_number;
	
	low_number = 3.3;
	high_number = 10.9;
	x = low_number + (high_number - low_number) * (rand() /1000) / 2.0;
	/*x = (float)(rand()% 100+ 1);*/
	printf("%f", x);
	return 0;
}

Edited 6 Years Ago by newbiecoder: n/a

This question has already been answered. Start a new discussion instead.