为什么下面这段代码在使用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

暂无数据
代码如下
#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;
}