-1

我有以下代码:

//#include all necessary things
class RandomGenerator {
public:
   double GetRandomDbl() {
     random_device rd;
     mt19937 eng(rd());
     std::uniform_real_distribution<double> dDistribution(0,1);
     return dDistribution(eng);
     }
 };

然后我有:

int _tmain(int argc, _TCHAR* argv[])
{
RandomGenerator Rand;    //on the heap for now

for (int i = 0; i < 1000000; i++) {
double pF = Rand.GetRandomDbl();
}
}

仅此代码,在 4GB RAM 上执行需要惊人的 25-28 秒。我记得每次使用 Mersenne twister 时都会阅读一些关于实例化新对象的内容,但如果这是问题所在,我应该如何改进呢?当然,这可以更快。

4

1 回答 1

2

您不需要在GetRandomDbl. 尝试这个:

//#include all necessary things
class RandomGenerator {
public:
    RandomGenerator() : eng(rd()), dDistribution(0, 1) {}

    double GetRandomDbl() {
        return dDistribution(eng);
    }
private:
    random_device rd;
    mt19937 eng;
    std::uniform_real_distribution<double> dDistribution;
};
于 2016-02-25T09:58:09.380 回答