-1

I have the following code:

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

And then I have:

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

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

This code alone, takes an astounding 25-28 seconds to execute on 4GB RAM. I recall reading something about instantiating a new object every time I use the Mersenne twister, but if that's the issue how should I improve this? Surely this can be made faster.

  • `random_device` is probably slow, and I've read previous questions on here about disappointing performance of Mersenne twister. Aside from keeping the objects alive instead of constructing them a million times (not hyperbole!), you could invest in faster prng. – Weak to Enuma Elish Feb 25 '16 at 10:05
  • Note that you aren't really using the Mersenne twister here at all. All the randomness is coming from random_device. – Martin Bonner supports Monica Feb 25 '16 at 10:08
  • I don't completely understand. Are you saying I could cut out constructing the mt19937 eng entirely? And if so, would that be a better pseudo random generator than using the mersenne twister on a seed such as time(0)? – SpelingError Feb 25 '16 at 10:17

1 Answers1

2

You do not need to create the pseudo random number generator objects in GetRandomDbl. Try this:

//#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;
};
Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36
user2807083
  • 2,962
  • 4
  • 29
  • 37