我应该保留随机分布对象实例还是可以始终重新创建它? [英] Should I keep the random distribution object instance or can I always recreate it?

查看:116
本文介绍了我应该保留随机分布对象实例还是可以始终重新创建它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

static std::mt19937 rnd;

// ...

static uint32_t rndInt(uint32_t min, uint32_t max) {
    return std::uniform_int_distribution<uint32_t>(min,max)(rnd);
}

这是一种好习惯还是应该存储uniform_int_distribution?

我怀疑分发对象的创建和销毁是否昂贵,尽管我认为它可能比仅存储参数min,max做得更多.它可能会根据参数预先计算一些有用的值,例如,在明显的实现中,2**32 % (max-min+1)是生成器中将被丢弃并重试的不同值的数量.

原则上,允许分配对象在其中存储一些熵,这些熵是在上一次调用operator()时从生成器中提取的,但不是必需的.这些位可用于以后的operator()调用.因此,如果min==0max==1,则在生成器上每次调用时,您可以在分发中获得32个对operator()的调用.这就是reset()函数的作用,以清除此状态.

因此,如果您重复使用相同的最小/最大值,那么从技术上讲,您每次都在使用新的分发方式来浪费随机位,与保留分发对象相比,对引擎的调用可能会更少大约.但是我怀疑这是否重要,特别是因为MT速度很快.

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?

解决方案

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 implementation 2**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 later operator() invocation. So if min==0 and max==1, then you can get 32 calls to operator() on the distribution per call on the generator. That's what the reset() 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.

这篇关于我应该保留随机分布对象实例还是可以始终重新创建它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆