【问题标题】:Overhead for single threaded OpenMP vs sequential单线程 OpenMP 与顺序的开销
【发布时间】:2014-11-12 16:58:08
【问题描述】:

我正在使用 OpenMP,但偶然发现了一些我不理解的东西。我正在使用以下并行代码(可以正常工作)。当使用两倍以上的线程时,它的执行时间几乎减半。但是,使用带有一个线程的 OpenMP 的执行时间是 35 秒,而当我评论 pragma 时,它会减少到 25 秒!我能做些什么来减少这个巨大的开销吗? 我正在使用 gcc 4.8.1 并使用“-O2 -Wall -fopenmp”进行编译。

我读过类似的主题(OpenMP with 1 thread slower than sequential versionOpenMP overhead)——意见不同,从没有开销到有很多开销。我很好奇在我的特定情况下(for 循环和并行for)是否有更好的方法来使用 OpenMP。

for (size_t k = 0 k < maxk; ++k) { // k is ~5000
    // init reduction variables
    const bool is_time_for_reduction = ;// init from k
    double mmin = INFINITY, mmax = -INFINITY;
    double sum = 0.0;


    #pragma omp parallel shared(m1, m2)
    {
       // w, h are both  between 1000 and 2000
        #pragma omp for
        for (size_t i = 0; i < h; ++i) { // w,h - consts
            for (size_t j = 0; j < w; ++j) {
                // computations with matrices m1 and m2, using only m1,m2 and constants w,h
            }
        }

        if (is_time_for_reduction) {
            #pragma omp for reduction (max/min/sum: mmax,mmin,sum)
            for (size_t i = 0; i < h; ++i) {
                for (size_t j = 0; j < w; ++j) {
                    // reductions
                }
            }
        }
    }


    if (is_time_for_reduction) {
        // use "reduced" variables
    }
}

【问题讨论】:

  • 查看带有和不带有编译指示的程序集。
  • 您是否尝试过我的答案中的代码,有无编译指示?编译器可能会以与您的版本不同的方式对其进行优化。

标签: c multithreading openmp


【解决方案1】:

我认为没有理由更改您的原始顺序代码。我会试试这个:

for (size_t k = 0 k < maxk; ++k) {
    // init reduction variables
    const bool is_time_for_reduction = ;// init from k
    double mmin = INFINITY, mmax = -INFINITY;
    double sum = 0.0;

    #pragma omp parallel for
    for (size_t i = 0; i < h; ++i) { // w,h - consts
        for (size_t j = 0; j < w; ++j) {
            // computations with matrices m1 and m2, using only m1,m2 and constants w,h
        }
    }

    if (is_time_for_reduction) {
       #pragma omp parallel for reduction (max/min/sum: mmax,mmin,sum)
       for (size_t i = 0; i < h; ++i) {
           for (size_t j = 0; j < w; ++j) {
               // reductions
           }
       }
       // use "reduced" variables
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2013-06-12
    • 1970-01-01
    • 2012-05-24
    • 2012-02-21
    相关资源
    最近更新 更多