我一直无法让线程化 C++ 随机数生成器在单核上优于标准 rand()。(我也看到多个线程调用 rand() 的问题)
我知道某处存在并发问题,但我看不到。我已经到了下面,我知道 openmp 正在拆分 8 个可用内核。当我注释掉 omp 行时,我会得到更快的结果。请帮忙!这真让我抓狂!
时代
Single thread
time ./a.out
real 0m3.497s
user 0m3.492s
sys 0m0.000s
OpemMP 8 cores
g++ -fopenmp randtests.cpp
time ./a.out
real 0m14.723s
user 1m52.275s
sys 0m0.712s
编码:
#include <omp.h>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include "boost/random.hpp"
using namespace std;
class RNG
{
public:
typedef boost::random::mt19937 Engine;
typedef boost::random::uniform_smallint<int> Distribution;
Engine engine;
Distribution distributer;
RNG() : engine(), distributer() {
engine.seed(); }
int operator()() {
return distributer(engine);
}
};
int main(void) {
#pragma omp parallel
{
int i = omp_get_thread_num();
unsigned int myseed = i;
RNG r;
int y;
#pragma omp for ordered schedule(dynamic) nowait
for (unsigned int x = 0; x < 100000000; x++) {
y = r();
}
}
return 0;
}