问题
I'm working on an algorithm which needs to generate millions of numbers as fast as possible. Actually I found out that the rand() function of my algorithm takes 75% of the process time.
So I'm looking for something faster. And I don't need a big range at all. (I only need integer numbers below 1000)
Do you know something I could use ?
Thanks !
Edit :
I use this numbers for shuffling groups of less than 1000 entities.
I found out more about the "fast rand". And there is SSE version version which is even faster and generates 4 numbers at a time.
https://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/
回答1:
static unsigned int g_seed;
// Used to seed the generator.
inline void fast_srand(int seed) {
g_seed = seed;
}
// Compute a pseudorandom integer.
// Output value in range [0, 32767]
inline int fast_rand(void) {
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
回答2:
Mersenne Twister algorithm is a quite fast yet balanced pseudo-random number generator.
Here is a sample implementation : http://fmg-www.cs.ucla.edu/geoff/mtwist.html
回答3:
If you are using Intel Ivy Bridge processor, you could very well offload random number generation to hardware using RDRAND instruction.
This stack overflow article talks about the throughput of RDRAND.
You could also identify if the processor supports RDRAND and use hardware offload or else fall back to software implementation.
回答4:
In most systems, rand() is a pseudo-random number generator. So the code should be just a few shift + bit-OR operations and able to produce millions of numbers per second on a typical PC. You don't say what you get and what your hardware is or which C library you're using, so it's hard to see why your implementation is "slow".
Maybe you can try to reuse bits: Take the lowest ten bits (= 1024 values), modulo 1000 to get the number range you want. Then shift and when you run out of bits, call rand() again for more bits.
来源:https://stackoverflow.com/questions/26237419/faster-than-rand