即使 num_threads(1) 时,openmp 的性能提升也难以理解

2024-03-14

下面几行代码

int nrows = 4096;
int ncols = 4096;
size_t numel = nrows * ncols;
unsigned char *buff = (unsigned char *) malloc( numel );

unsigned char *pbuff = buff;
#pragma omp parallel for schedule(static), firstprivate(pbuff, nrows, ncols), num_threads(1)
for (int i=0; i<nrows; i++)
{
    for (int j=0; j<ncols; j++)
    {
        *pbuff += 1;
        pbuff++;
    }
}

编译时需要 11130 usecs 在我的 i5-3230M 上运行

g++ -o main main.cpp -std=c++0x -O3

也就是说,当 openmp 编译指示被忽略时。

另一方面,编译时只需要 1496 usecs

g++ -o main main.cpp -std=c++0x -O3 -fopenmp

速度快了 6 倍多,考虑到它是在 2 核机器上运行,这是相当令人惊讶的。事实上,我也测试过线程数(1)而且性能的提升还是相当重要的(快了3倍以上)。

任何人都可以帮助我理解这种行为吗?

编辑:根据建议,我提供完整的代码:

#include <stdlib.h>
#include <iostream>

#include <chrono>
#include <cassert>


int nrows = 4096;
int ncols = 4096;
size_t numel = nrows * ncols;
unsigned char * buff;


void func()
{
    unsigned char *pbuff = buff;
    #pragma omp parallel for schedule(static), firstprivate(pbuff, nrows, ncols), num_threads(1)
    for (int i=0; i<nrows; i++)
    {
        for (int j=0; j<ncols; j++)
        {
            *pbuff += 1;
            pbuff++;
        }
    }
}


int main()
{
    // alloc & initializacion
    buff = (unsigned char *) malloc( numel );
    assert(buff != NULL);
    for(int k=0; k<numel; k++)
        buff[k] = 0;

    //
    std::chrono::high_resolution_clock::time_point begin;
    std::chrono::high_resolution_clock::time_point end;
    begin = std::chrono::high_resolution_clock::now();      
    //
    for(int k=0; k<100; k++)
        func();
    //
    end = std::chrono::high_resolution_clock::now();
    auto usec = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();
    std::cout << "func average running time: " << usec/100 << " usecs" << std::endl;

    return 0;
}

事实证明,答案是firstprivate(pbuff, nrows, ncols)有效地声明pbuff, nrows and ncols作为 for 循环范围内的局部变量。这反过来意味着编译器可以看到nrows and ncols作为常量 - 它不能对全局变量做出相同的假设!

因此,随着-fopenmp,你最终会得到巨大的加速,因为您没有在每次迭代中访问全局变量。 (另外,有一个常数ncols值,编译器会进行一些循环展开)。

通过改变

int nrows = 4096;
int ncols = 4096;

to

const int nrows = 4096;
const int ncols = 4096;

or通过改变

for (int i=0; i<nrows; i++)
{
    for (int j=0; j<ncols; j++)
    {
        *pbuff += 1;
        pbuff++;
    }
}

to

int _nrows = nrows;
int _ncols = ncols;
for (int i=0; i<_nrows; i++)
{
    for (int j=0; j<_ncols; j++)
    {
        *pbuff += 1;
        pbuff++;
    }
}

异常加速消失 - 非 OpenMP 代码现在与 OpenMP 代码一样快。

这个故事的主旨?避免访问性能关键循环内的可变全局变量。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使 num_threads(1) 时,openmp 的性能提升也难以理解 的相关文章

随机推荐