问题
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