hi....i'm trying to write a code that generate random numbers quickly because i'll iterate my code a lot of times.....millions of times....
I use srand(time(NULL)) to initialize the seed, and random(RAND_MAX) to generate the random number, but this form is annormally slow
I need help to reduce the time of execution because millions of iterations retard too my program using "random"
Excuse me for my english...thanks!!!

Recommended Answers

All 4 Replies

call srand() only once during the lifetime of the program -- normally called near the beginning of main().

ok thanks, but I call srand() only once....i continue waiting for your responses thanks.....

~35 millions pseudo-random numbers per second with VC++ 2008 compiler - are you sure that it's too slow for your application?
Well, look at http://www.firstpr.com.au/dsp/rand31/
or simply try Google "fast pseudorandom generator" - tons of links ;)

rand() should be pretty quick, because it is pretty simple.

You might try

for ( i = 0 ; i < 1E7 ; i++ ) {
    num = 42;  // was num = rand();
}

Just to make sure that it's rand() which is the bottleneck, and not something else in your code.

You wouldn't be the first person to guess wrong as to where the performance issues really are.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.