定义概率分布成本高吗? [英] Is defining a probability distribution costly?

查看:64
本文介绍了定义概率分布成本高吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写物理模拟代码,现在觉得需要对其进行优化.我正在考虑改进一点:我的一个班级的一种方法(在几种情况下我称之为十亿次)每次都定义概率分布.代码如下:

I'm coding a physics simulation and I'm now feeling the need for optimizing it. I'm thinking about improving one point: one of the methods of one of my class (which I call a billion times in several cases) defines everytime a probability distribution. Here is the code:

void myClass::myMethod(){ //called billions of times in several cases
uniform_real_distribution<> probd(0,1);
uniform_int_distribution<> probh(1,h-2);
uniform_int_distribution<> probv(1,v-2);
    //rest of the code
}

我可以将分发作为类的成员传递,这样我就不必每次都定义它们吗?并在构造函数中初始化它们并在 h 和 v 更改时重新定义它们?可以是一个很好的优化进度吗?最后一个问题,当使用标志 -O3 或 -O2 编译时,它是否已经被编译器(在我的例子中为 g++)纠正了?

Could I pass the distribution as member of the class so that I won't have to define them everytime? And just initialize them in the constructor and redefine them when h and v change? Can it be a good optimizing progress? And last question, could it be something that is already corrected by the compiler (g++ in my case) when compiled with flag -O3 or -O2?

先谢谢你!

更新:我对它进行了编码并对两者进行了计时:程序实际上变慢了一些(几个百分点)所以我又回到了我开始的地方:在每个循环中创建概率分布

Update: I coded it and timed both: the program turned actually a bit slower (a few percents) so I'm back at what I started with: creating the probability distributions at each loop

推荐答案

Answer A:我不应该这么认为,对于均匀分布,它只是将参数值复制到位,可能需要少量算术,这将得到很好的优化.

Answer A: I shouldn't think so, for a uniform distribution it's just going to copy the parameter values into place, maybe with a small amount of arithmetic, and that will be well optimized.

不过,我相信分布对象可以有状态.他们可以使用来自对生成器的调用的部分随机数据,并被允许保存其余的随机性以在下次使用分布时使用,以减少对生成器的调用总数.因此,当您销毁分发对象时,您可能会丢弃一些可能代价高昂的随机数据.

However, I believe distribution objects can have state. They can use part of the random data from a call to the generator, and are permitted save the rest of the randomness to use next time the distribution is used, in order to reduce the total number of calls to the generator. So when you destroy a distribution object you might be discarding some possibly-costly random data.

答案 B:停止猜测并进行测试.

Answer B: stop guessing and test it.

为您的代码计时,然后将 static 添加到 probd 的定义中并再次计时.

Time your code, then add static to the definition of probd and time it again.

这篇关于定义概率分布成本高吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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