【问题标题】:Why old rand() faster than uniform_real_distribution in openMP?为什么旧 rand() 比 openMP 中的 uniform_real_distribution 快?
【发布时间】:2021-01-01 10:09:03
【问题描述】:

有人可以向我解释为什么第二个 for 循环使用旧的 rand() 比第一个循环执行得快很多吗?我在这里通过多个帖子看到,推荐使用 c++11 引擎和均匀分布,因为 rand() + 多线程是性能瓶颈? 同样按照建议,我每个线程都有生成器和函数。

int main(int argc, char *argv[])
{

    std::vector<mt19937> generators(omp_get_max_threads());
    std::vector<uniform_real_distribution<double>> functions(omp_get_max_threads());
    
    for (int i = 0; i < omp_get_max_threads(); i++)
    {
        // seed is random
        generators[i] =  mt19937(1654 + 17*i);
        functions[i] =   uniform_real_distribution<double>(0.0,1.0);
    }

    double itime = omp_get_wtime();
    #pragma omp parallel for        
        for (int i =0; i < 10000000; i++)
        {
            int a = functions[omp_get_thread_num()](generators[omp_get_thread_num()]);
        }
        
    
    double end = omp_get_wtime() - itime;
    
    srand(time(NULL));
    double start = omp_get_wtime();
        #pragma omp parallel for
        for (int i =0; i < 10000000; i++)
        {
            int a = ((double) rand() / (RAND_MAX));
        }
    double endR  = omp_get_wtime() - start;

    cout << "Generator: " << end<<endl;
    cout<<"Old: "<<endR << endl;
}

【问题讨论】:

标签: c++ performance random parallel-processing openmp


【解决方案1】:

cmets 提出了类似的建议

struct alignas(std::hardware_destructive_interference_size) Rng {
   std::mt19937 mers;
  std::uniform_real_distribution<double>> dist;
};

std::vector<Rng> rngs(omp_get_max_threads());

而且我隐约记得omp 有一种方法可以为每个块设置一个值,所以omp_get_thread_num() 一直都是这样,这也可能使每个结构 Rng 的引用成为可能。

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 2014-12-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2019-04-02
    相关资源
    最近更新 更多