#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
using namespace std;
void output(float a[], float X[], float Y[], int I, int J)
{
ofstream ft;
int i;
ft.open("flow.dat");
ft<<"variables=\"x\",\"y\",\"a\""<<"\n"
<<"zone f=point"<<"\n"
<<"I="<<I<<",J="<<J<<"\n"
<<endl;
for(int i=0;i<I*J;i++)
{
ft<<setiosflags(ios::scientific)
<<X[i]<<" "<<Y[i]<<" "<<a[i]<<endl;
}
ft.close();
}
void set(float a[], float X[], float Y[], int I, int J, float hx, float hy)
{
for(int j=0;j<J;j++)
for(int i=0;i<I;i++)
{
int iC=j*I+i;
X[iC]=i*hx;
Y[iC]=j*hy;
a[iC]=0.0;
if(j==J-1) a[iC]=1.0;
}
}
void difference_serial(float a[], int I, int J, const float hx, const float hy)
{
const float aC=(hx*hx+hy*hy)*2;
const float aX=hy*hy;
const float aY=hx*hx;
for(int j=1;j<J-1;j++)
for(int i=1;i<I-1;i++)
{
int iC=j*I+i;
int iL=iC-1;
int iR=iC+1;
int iU=iC+I;
int iD=iC-I;
a[iC]=(aX*(a[iL]+a[iR])+aY*(a[iU]+a[iD]))/aC;
}
}
void difference_omp(float a[], int I, int J, const float hx, const float hy)
{
const float aC=(hx*hx+hy*hy)*2;
const float aX=hy*hy;
const float aY=hx*hx;
int i,j,iC,iL,iR,iU,iD;
#pragma omp parallel for private(i,j,iC,iL,iR,iU,iD) shared(a,I,J) schedule(dynamic)
for(j=1;j<J-1;j++)
for(i=1;i<I-1;i++)
{
iC=j*I+i;
iL=iC-1;
iR=iC+1;
iU=iC+I;
iD=iC-I;
a[iC]=(aX*(a[iL]+a[iR])+aY*(a[iU]+a[iD]))/aC;
}
}
int main()
{
const int I=129;
const int J=129;
const int N=I*J;
const float hx=1.0/(I-1);
const float hy=1.0/(J-1);
float *a=new float[N];
float *X=new float[N];
float *Y=new float[N];
//set the grid and flow
set(a,X,Y,I,J,hx,hy);
//iteation
clock_t start=clock();
for(int it=0;it<10000;it++)
difference_serial(a,I,J,hx,hy);
clock_t end=clock();
printf("Serial time=%f\n",(float)(end-start)/CLOCKS_PER_SEC);
set(a,X,Y,I,J,hx,hy);
clock_t start2=clock();
for(int it2=0;it2<10000;it2++)
difference_omp(a,I,J,hx,hy);
clock_t end2=clock();
printf("Omp time=%f\n",(float)(end2-start2)/CLOCKS_PER_SEC);
//output
output(a,X,Y,I,J);
//free memory
delete[] a;
delete[] X;
delete[] Y;
}
我写了一段代码来解决二维非常简单的拉普拉斯方程。试比较串行代码和OpenMP代码为什么我的OpenMP C++代码比串行代码慢?
我试图编译 G ++ tmp.cpp -fopenmp
的代码,并得到了非常奇怪的结果 输出: 串行时间= 1.620000 外膜蛋白时间= 9.820000
有没有人可以帮助我找出背后的原因以及如何纠正OpenMP代码。
你正在测量CPU时间,而不是“挂钟”时间http://en.wikipedia.org/wiki/Wall_clock_time – CharlesB 2013-03-04 16:38:28
这是一个问题,但它没有原来的问题。我拿了代码,并将时间测量值改为'omp_get_wtime()',但它仍然为我的PC提供了omp time 13s和serial 3s。我猜这是平行区域instatation开销。 – luk32 2013-03-04 16:47:26