使用Mersenne twister进行随机双代的性能问题

时间:2016-02-25 09:50:56

标签: c++ random mersenne-twister

我有以下代码:

$dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');

$sth = $dbh->prepare("SELECT steam_id FROM users");
$sth->execute();
while($result = $sth->fetch())
{
    $steamids = $result['steam_id'];
    $APIKEY = '*******';
    $steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=$steamids&key=$APIKEY&format=json";
    $json_object= file_get_contents($steamAPI);
    echo $json_object;
}

然后我有:

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

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

1 个答案:

答案 0 :(得分: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;
};