C++: Performance for drawing random boolean values

末鹿安然 提交于 2021-01-28 06:40:53

问题


I am drawing random boolean numbers with

std::mt19937 rng;
std::uniform_int_distribution<int> dis(0, 1);

In extreme cases, drawing these numbers can take up to 40% of the CPU time of my process. Is there any way to make this faster?


回答1:


I would get rid of uniform_int_distribution.

One invocation of std::mt19937::operator() (i.e. doing rng()) will give you 32 random bits, which you can use one by one.

A benchmark shows that this method is about 23 times faster.




回答2:


You might be happy with @HolyBlackCat answer, but for sampling such values there is a Bernoulli distribution support in C++

Along the lines

std::mt19937 rng{1234567};
std::bernoulli_distribution bd{0.5};

std::cout << bd(rng) << '\n';
std::cout << bd(rng) << '\n';
std::cout << bd(rng) << '\n';


来源:https://stackoverflow.com/questions/57227028/c-performance-for-drawing-random-boolean-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!