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

查看:119
本文介绍了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\n", 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天全站免登陆