After profiling a large game playing program, I have found that the library function rand() is consuming a considerable fraction of the total processing time. My requirements for the random number generator are not very onerous - its not important that it pass a great battery of statistical tests of pure randomness. I just want something cheap and cheerful that is very fast. Any suggestions?
For "not too random" integers, you could start with the current UNIX time, then use the recursive formula r = ((r * 7621) + 1) % 32768; . The nth random integer between 0 (inclusive) and M (exclusive) would be r % M after the nth iteration. This is called a linear congruential generator.
However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767).
There are few algorithms in common use that are faster than an LCG (which is very, very likely what rand()
is using). You may want to try Marsaglia's Xorshift generator which is pretty fast (depending on the hardware). The WELL512a generator is also quite fast (more so than MT19937 or MT19937-64).
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