I have this code:
static std::mt19937 rnd;
// ...
static uint32_t rndInt(uint32_t min, uint32_t max) {
return std::uniform_int_distribution<uint32_t>(min,max)(rnd);
}
Is that good practice or should I store the uniform_int_distribution?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I doubt that the distribution object is expensive to create and destroy, although I suppose it might do slightly more than just store the parameters
min,max. It might precalculate some useful values based on the parameters, for instance in the obvious implementation2**32 % (max-min+1)is the number of different values from the generator that would be discarded and re-tried.In principle, a distribution object is allowed to store inside it some bits of entropy that were drawn from the generator on a previous call to
operator(), but not needed. Those bits could be used for a lateroperator()invocation. So ifmin==0andmax==1, then you can get 32 calls tooperator()on the distribution per call on the generator. That’s what thereset()function is about, to clear this state.So if you use the same min/max values repeatedly, then technically you’re wasting random bits by using a new distribution each time — you could perhaps end up with fewer calls to the engine than if you kept the distribution object around. But I doubt it matters, especially since MT is fast.