c++ - OpenMP:嵌套 for 循环,执行时间几乎没有差异

标签 c++ visual-c++ parallel-processing openmp

我正在做一些图像处理并且有一个嵌套的 for 循环。我想使用 OpenMP 实现多处理。 for 循环看起来像这样,我在其中添加了 pragma 标记并将一些变量声明为私有(private)。

int a,b,j, idx;
#pragma omp parallel for private(b,j,sumG,sumGI)
    for(a = 0; a < ny; ++a) 
    {
        for(b = 0; b < nx; ++b) 
        {
            idx = a*ny+b;
            if (imMask[idx] == 0) 
            {
                Wshw[idx] = 0;
                continue;
            }

            sumG = 0;
            sumGI = 0;

            for(j = a; j < ny; ++j) 
            {
                sumG += shadowM[j-a];
                sumGI += shadowM[j-a] * imBlurred[nx*j + b];
            }

            Wshw[idx] = sumGI / sumG;
        }
    }

nx 和 ny 的大小都很大,我认为使用 OpenMP,执行时间会下降,但实际上几乎没有区别。当我实现多线程时,我做错了什么吗?

最佳答案

你在 idx 中有一个竞争条件。您还需要将其设为私有(private)。

但是,您可以尝试这样的操作。

int a,b,j, idx;
#pragma omp parallel for private(a,b,j,sumG,sumGI)
for(idx=0; idx<ny*nx; ++idx) { 
    if (imMask[idx] == 0) 
    {
        Wshw[idx] = 0;
        continue;
    }

    sumG = 0;
    sumGI = 0;
    a=idx/ny;
    b=idx%ny;
    for(j = a; j < ny; ++j) {
        sumG += shadowM[j-a];
        sumGI += shadowM[j-a] * imBlurred[nx*j + b];
    }

    Wshw[idx] = sumGI / sumG;
}

您可以简单地使用内部循环以及 idx 函数代替 a 和 b。

关于c++ - OpenMP:嵌套 for 循环,执行时间几乎没有差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21637498/

相关文章:

Visual Studio 中的C++

c++ - POD 的 WinAPI union 双关语到基本类型 : Implementation dependent or standard compliant?

PHP - 使用 multi_curl 进行并行处理是个好主意吗?

multithreading - 我应该并行化多少代码执行?

c++ - 使用 thrift 和 cassandra 编译 C++ 程序

c++ - 如何同时打开多个文件以在c中读取

c++ - 给定表达式 : `cond ? *this : throw()` 返回对类型的引用时出错

c++ - 复制对象时,带有 MSVC 2010 Debug 的 OpenMP 会生成奇怪的错误

c++ - 需要在c++中以周期性时间间隔调用函数

parallel-processing - 数据多核并行计算,随程序独立运行