Pustovalov Dmitry Pustovalov Dmitry - 2 months ago 5x
C++ Question

c++11 random engines and distributions interaction and cost

I have a bunch of questions about random engines and distributions, their cost and interaction:

  1. Is
    an expensive (heavy constructible) object? Should I only create one for my application if possible?

  2. Are
    objects expensive objects or is it mostly dependent of concrete distribution? It seems to me that for example
    should be very light object containing distribution range
    [min, max]
    and may be (?) some internal state.

  3. How does the interaction between
    work in code below:

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(1, 10);

    auto random_value = distr(gen);

What happens in last line? Distribution get next value from random engine and then brings it to desired range
[0, 10]
? Always obviously internal states of some objects should be modified after call: definitely
but does
also have some internal state?


1) Usually it isn't, initialization either is trivial or comaprable to some PRNG initialization, however invoking operator() might access OS for secure random number and it could be costly.

2) Mostly depends on distribution. They containg distribution parameters (which you can retrieve if you want) and optionally some inner state (IIRC most implementation doesn't bother with it). So initializating distribution is like initializating small structure.

3) Distribution object invokes generators operator() unspecified amount of times (from 0 to ∞ times) and creates a random number from bit sequence produced by generator. Then it returns generated bumber. It potentially advances generator state and might store unused bits produced by generator in distribution internal state.

random_device, probably, does not even has internal state, if it implemented as handle to system RNG. Otherwise, its state is advanced on second line, when you invoke its operator() to produce random number you will use as seed for your generator.