OpenMP 程序比顺序程序慢 [英] OpenMP program is slower than sequential one

查看:24
本文介绍了OpenMP 程序比顺序程序慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试以下代码时

double start = omp_get_wtime();

long i;

#pragma omp parallel for
    for (i = 0; i <= 1000000000; i++) {
        double x = rand();
    }

    double end = omp_get_wtime();

    printf("%f
", end - start);

执行时间约为 168 秒,而顺序版本仅花费 20 秒.

Execution time is about 168 seconds, while the sequential version only spends 20 seconds.

我还是并行编程的新手.我怎样才能获得比顺序版本更快的并行版本?

I'm still a newbie in parallel programming. How could I get a parallel version that's faster that the sequential one?

推荐答案

随机数生成器 rand(3) 使用全局状态变量(隐藏在 (g)libc 实现中).从多个线程访问它们会导致缓存问题并且也不是线程安全的.您应该使用 rand_r(3) 调用和线程私有的 seed 参数:

The random number generator rand(3) uses global state variables (hidden in the (g)libc implementation). Access to them from multiple threads leads to cache issues and also is not thread safe. You should use the rand_r(3) call with seed parameter private to the thread:

long i;
unsigned seed;

#pragma omp parallel private(seed)
{
    // Initialise the random number generator with different seed in each thread
    // The following constants are chosen arbitrarily... use something more sensible
    seed = 25234 + 17*omp_get_thread_num();
    #pragma omp for
    for (i = 0; i <= 1000000000; i++) {
       double x = rand_r(&seed);
    }
}

请注意,这将在并行执行时与串行执行时产生不同的随机数流.我还推荐 erand48(3) 作为更好的(伪)随机数源.

Note that this will produce different stream of random numbers when executed in parallel than when executed in serial. I would also recommend erand48(3) as a better (pseudo-)random number source.

这篇关于OpenMP 程序比顺序程序慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆