应该通过引用传递随机分布还是应该成为c ++中的对象成员 [英] Should random distributions be passed by reference or be object members in c++

查看:45
本文介绍了应该通过引用传递随机分布还是应该成为c ++中的对象成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们只实例化少于20个Blob类的对象,并考虑效率(时间执行)和内存管理问题,是否有最佳选择:

Assuming we only instantiate less than 20 objects of class Blob and regarding efficiency (time execution) and memory management issues, is there a best option between:

  • 将随机生成器和生成的分布设置为私有类成员,例如:

  • Setting the random generator and the generated distributions as private class members such as:

class Blob {
private:
std::mt19937 engine;
std::uniform_real_distribution<double> R_distribution;
std::binomial_distribution<int> B_distribution;
}

并直接在Blob方法中使用它们.因此,当我们调用发行版时,我们还更改了作为成员的引擎的状态.

and using them directly in Blob methods. Thus when we call a distribution, we also alter the state of the engine that is a member.

还是将随机生成器设置为私有类成员,并通过引用方法将分布传递?例如:

Or setting the random generator as a private class members and passing the distributions by reference to the methods? For instance:

class Blob {
private:
std::mt19937 engine; //engine
}

void Blob::run() {
int blabla = 10;
std::uniform_real_distribution<double> R_distribution(0, 10);
do_something(blabla, R_distribution);
...
}

虽然通过引用传递通常会导致较低的开销,但是在这种情况下尤其重要吗?调用分布多次(10 ^ 9或更多次)时,总体问题如何缩放?

While passing by reference induce lower overhead in general, does it matter in that case in particular? How does the overall question scale when calling the distributions a huge number of times (10^9 or more)?

推荐答案

发行版很便宜,可以随意创建/删除.引擎不是.理想情况下,如果您的程序是多线程的,则应该仅一次一次初始化PRNG,并确保它为thread_local. PRNG像std::mt19937一样庞大,并且具有很大的内部状态.考虑做这样的事情:

Distributions are cheap and can be created/tossed away willy-nilly. Engines are not. Ideally, you should only initialize your PRNG once and ensure it is thread_local if your program is multithreaded. PRNG's like std::mt19937 are bulky and have a large internal state. Consider doing something like this:

inline auto global_rng() -> std::mt19937& {
    thread_local std::mt19937 e{ get_seed() };
    return e;
}

void foo() {
    thread_local std::uniform_real_distribution<double> d; 
    // ...
}

这篇关于应该通过引用传递随机分布还是应该成为c ++中的对象成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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