简体   繁体   English

C++ 快速生成大量随机浮点数(10,000+ 个数字)

[英]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.对于我目前正在进行的一个项目,我需要尽可能快地生成大量介于 0 和 1 之间的伪随机浮点数,范围在数千到数十万之间。

What would the best method for this be?最好的方法是什么?

The options I can think of currently are:目前我能想到的选项有:

C rand() , Quite fast from my experience. C rand() ,根据我的经验相当快。

C++11 Random, rather slow but better random numbers from what I have heard. C++11 随机,从我听说的情况来看,随机数相当慢但更好。

A custom hash function such as:自定义 hash function 如:

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.我唯一能想到的是一些更快的 hash 或以某种方式通过计算着色器在 GPU 上执行此操作,但我在这方面没有太多经验。

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.如果速度是唯一的考虑因素,那么最快的解决方案是return 0.0 ,尽管分布相当有偏差。

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. <random>包括一些生成器,其中一些非常简单和快速。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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