简体   繁体   中英

C++ generate large amounts of random floats(10,000+ numbers) fast

For a project I am currently working on I need to generate a large amount of pseudorandom floating-point numbers, between 0 and 1, in the range of thousands to hundreds of thousands as fast as possible.

What would the best method for this be?

The options I can think of currently are:

C rand() , Quite fast from my experience.

C++11 Random, rather slow but better random numbers from what I have heard.

A custom hash function such as:

u_int32_t seed = 1;
seed = (seed ^ 61) ^ (seed >> 16);
seed = seed + (seed << 3);
seed = seed ^ (seed >> 4);
seed = seed * 0x27d4eb2d;
seed = seed ^ (seed >> 15);
uint8_t a = seed&0xff;
float n = (((float)a)/UINT8_MAX);

Which is quite fast.

Speed test for the above:

Generating 100000 Random Numbers
C rand(): 1.72661
C++ random: 6.60626
hash random: 1.034

Are there any faster options? The only thing I can think of are some quicker hash or somehow doing it on the GPU via a compute shader, but I don't have much experience in that.

Any help is most appreciated.

Edit: Just to clarify, the times above are in milliseconds.

What would the best method for this be?

Depends on other requirements besides the speed. Does the sequence need to be reproducible? Does the statistical quality of randomness matter? Does the distribution need to be uniform? What processor will you be using to execute the program?

If the speed is the only consideration, then the fastest solution is return 0.0 , although the distribution is quite biased.

More seriously though, if statistical quality matters at least a little bit, enough that constant value is not sufficient, but still much less than speed, then the best way to choose the generator is to benchmark the known algorithms and pick the one that is fastest on your target system. <random> includes a few generators, some of which are quite simple and fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM