What is performance-wise the best way to generate random bools?

前端 未结 9 2196
滥情空心
滥情空心 2020-12-23 21:14

I need to generate random Boolean values on a performance-critical path.

The code which I wrote for this is

std::random_device   rd;
std::uniform_int         


        
9条回答
  •  清酒与你
    2020-12-23 22:16

    A way would be to just generate a unsigned long long for every 64 random calls as stated in the comments. An example:

    #include 
    class Randomizer
    {
    public:
        Randomizer() : m_rand(0), counter(0), randomizer(0, std::numeric_limits::max()) {}
    
        bool RandomBool()
        {
            if (!counter)
            {
                m_rand = randomizer(std::mt19937(rd()));
                counter = sizeof(unsigned long long) * 8;
    
            }
            return (m_rand >> --counter) & 1;
        }
    private:
        std::random_device  rd;
        std::uniform_int_distribution randomizer;
        unsigned long long m_rand;
        int counter;
    };
    

提交回复
热议问题