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

前端 未结 9 2175
滥情空心
滥情空心 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 21:59

    iI think that best way is an using of precalculated random array:

    uint8_t g_rand[UINT16_MAX];
    bool InitRand()
    {
        for (size_t i = 0, n = UINT16_MAX; i < n; ++i)
            g_rand[i] = ::rand() & 1;
        return true;
    }
    bool g_inited = InitRand();
    inline const uint8_t * Rand()
    {
        return g_rand + (::rand()&INT16_MAX);
    }
    

    It using to fill some array dst[size]:

    const size_t size = 10000;
    bool dst[size];
    for (size_t i = 0; i < size; i += INT16_MAX)
         memcpy(dst + i, Rand(), std::min(INT16_MAX, size - col));
    

    Of course you can initialize pre-calculated array with using of another random function.

提交回复
热议问题