使用梅森捻线机随机双生成的性能问题

Performance issue with random double generation using Mersenne twister

本文关键字:性能 问题 双生 随机 捻线机      更新时间:2023-10-16

我有以下代码:

//#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();
}
}

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

不需要

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;
};