其他
使用openmp效果差,甚至比串行慢
2023-06-03 14:34:40
138

为什么下面这段代码在使用openmp以后没有什么效果,在编译选项不加-O优化选项的情况下比串行慢很多。使用编译优化选项后也只在4个线程以下会有一点优化效果,并且把数据量提高到512 * 512 * 512使用omp与串行相比也无明显差距

无编译优化选项效果
g++ -fopenmp testarray.cpp -o testarray
noomp:0.317568
omp:0.278797

-O2优化选项+4线程效果
g++ --O2 fopenmp testarray.cpp -o testarray
noomp:0.0408151
omp:0.03548

512 * 512 * 512数据规模,4个线程,增加线程个数速度无提升
g++ --O2 fopenmp testarray.cpp -o testarray
noomp:0.317568
omp:0.278797

全部评论(3)
只看楼主
网
网友gtBK4p
楼主
1楼

代码如下

#include <iostream>

using namespace std;

#ifdef _OPENMP

#include <omp.h>

#endif

#define NXT 256

#define NYT 256

#define NZT 256

#include <sys/time.h>

#include<stdlib.h>

double cpuSecond()

{

struct timeval tp;

gettimeofday(&tp, NULL);

return (double)tp.tv_sec + (double)tp.tv_usec * 1.e-6;

}

int main()

{

double *p, *u, *v, *w;

p = (double *)malloc((NXT + 2) * (NYT + 2) * (NZT + 2) * sizeof(double));

u = (double *)malloc((NXT + 2) * (NYT + 2) * (NZT + 2) * sizeof(double));

v = (double *)malloc((NXT + 2) * (NYT + 2) * (NZT + 2) * sizeof(double));

w = (double *)malloc((NXT + 2) * (NYT + 2) * (NZT + 2) * sizeof(double));

int id;

int nyz, nyt, nzt;

nyt = NYT + 2;

nzt = NZT + 2;

nyz = nyt * nzt;

double t1, t2;

for (int i = 1; i <= NXT; i++)

for (int j = 1; j <= NYT; j++)

for (int k = 1; k <= NZT; k++)

{

id = i * nyz + j * nzt + k;

p[id] = 1.0;

u[id] = 1.0;

v[id] = 1.0;

w[id] = 1.0;

}

t1 = cpuSecond();

for (int i = 1; i <= NXT; i++)

for (int j = 1; j <= NYT; j++)

for (int k = 1; k <= NZT; k++)

{

id = i * nyz + j * nzt + k;

p[id] = 1.0;

u[id] = 1.0;

v[id] = 1.0;

w[id] = 1.0;

}

t2 = cpuSecond();

cout << " noomp:" << t2 - t1 << endl;

t1 = cpuSecond();

#pragma omp parallel

{

#pragma omp for

for (int i = 1; i <= NXT; i++)

for (int j = 1; j <= NYT; j++)

for (int k = 1; k <= NZT; k++)

{

id = i * nyz + j * nzt + k;

p[id] = 1.0;

u[id] = 1.0;

v[id] = 1.0;

w[id] = 1.0;

}

}

t2 = cpuSecond();

cout << " omp:" << t2 - t1 << endl;

return 0;

}
2023/6/3
网
网友zRCyFD
回复 @网友gtBK4p

我不太确定这个三层循环的结构,OpenMP能不能很好的展开。

另外CPU OpenMP可以使用Intel编译器试一下,会比gomp性能好一些
2023/6/5
网
网友gtBK4p
回复 @网友gtBK4p
我把三层循环改成一层循环用omp加速,在小的demo里面使用32个线程,加速效果能到8,9倍,同样的代码段同样的规模放到别的程序里面,为什么加速效果只有0.5倍,这一般是什么原因:xiaoku:emoji
2023/6/8
没有更多内容了
--
楼主
Level.4
0 帖子
楼主热帖
暂无数据