以下代码行
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
在编译时使用11130 usecs在我的i5-3230M上运行
g++ -o main main.cpp -std=c++0x -O3
Run Code Online (Sandbox Code Playgroud)
也就是说,当openmp pragma被忽略时.
另一方面,编译时只需要1496个usecs
g++ -o main main.cpp -std=c++0x -O3 -fopenmp
Run Code Online (Sandbox Code Playgroud)
这速度提高了6倍以上,考虑到它是在2核机器上运行,这是非常令人惊讶的.事实上,我也用num_threads(1)对它进行了测试,性能提升仍然非常重要(速度提高了3倍多).
有人可以帮我理解这种行为吗?
编辑:按照建议,我提供完整的代码: …