c++performanceoptimizationrandommt19937

How computationally expensive is generating a random number in C++?


The method that I am considering is from an answer to Generating random integer from a range.

#include <random>

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);

I'm also willing to use the rand() approach with srand(time(NULL)).

How expensive are these approaches? Is one much faster than the other?


Solution

  • Performance depends greatly on the generator you use (which in turn depends greatly on the quality of the numbers you need).

    For example, std::mt19937 is much faster than std::random_device, but it produces pseudo random numbers. This is fine for most purposes, if you don't need cryptographically safe random numbers. But even if you do, random_device can produce raw entropy at a rate of about 50 MB/sec on my machine—how much randomness do you really need? (mt19937 generates about orders of magnitudes more than that if needed).

    Avoid rand(). It just has very poor properties and a very low period.

    See also Rand Considered Harmful.