【发布时间】:2013-10-05 09:30:46
【问题描述】:
我正在学习 OPENMP 并编写了以下代码来解决 nqueens 问题。
//Full Code: https://github.com/Shafaet/Codes/blob/master/OPENMP/Parallel%20N- Queen%20problem.cpp
int n;
int call(int col,int rowmask,int dia1,int dia2)
{
if(col==n)
{
return 1;
}
int row,ans=0;
for(row=0;row<n;row++)
{
if(!(rowmask & (1<<row)) & !(dia1 & (1<<(row+col))) & !(dia2 & (1<<((row+n-1)-col))))
{
ans+=call(col+1,rowmask|1<<row,dia1|(1<<(row+col)), dia2|(1<<((row+n-1)-col)));
}
}
return ans;
}
double parallel()
{
double st=omp_get_wtime();
int ans=0;
int i;
int rowmask=0,dia1=0,dia2=0;
#pragma omp parallel for reduction(+:ans) shared(i,rowmask)
for(i=0;i<n;i++)
{
rowmask=0;
dia1=0,dia2=0;
int col=0,row=i;
ans+=call(1,rowmask|1<<row,dia1|(1<<(row+col)), dia2|(1<<((row+n-1)-col)));
}
printf("Found %d configuration for n=%d\n",ans,n);
double en=omp_get_wtime();
printf("Time taken using openmp %lf\n",en-st);
return en-st;
}
double serial()
{
double st=omp_get_wtime();
int ans=0;
int i;
int rowmask=0,dia1=0,dia2=0;
for(i=0;i<n;i++)
{
rowmask=0;
dia1=0,dia2=0;
int col=0,row=i;
ans+=call(1,rowmask|1<<row,dia1|(1<<(row+col)), dia2|(1<<((row+n-1)-col)));
}
printf("Found %d configuration for n=%d\n",ans,n);
double en=omp_get_wtime();
printf("Time taken without openmp %lf\n",en-st);
return en-st;
}
int main()
{
double average=0;
int count=0;
for(int i=2;i<=13;i++)
{
count++;
n=i;
double stime=serial();
double ptime=parallel();
printf("OpenMP is %lf times faster for n=%d\n",stime/ptime,n);
average+=stime/ptime;
puts("===============");
}
printf("On average OpenMP is %lf times faster\n",average/count);
return 0;
}
并行代码已经比普通代码快,但我想知道如何使用 openmp pragma 对其进行更多优化。我想知道为了更好的性能我应该做什么,不应该做什么。
提前致谢。
(请不要提出任何与并行编程无关的优化)
【问题讨论】:
-
您可以查看 RosettaCode 上的 this code。我首先在 F77 中编写它,然后将其改编为使用 OpenMP。它只使用“并行”,就像你的一样。但老实说,如果您不更改算法,除了在多个内核上并行运行(应该已经通过并行运行完成)之外,对 OpenMP 有什么期望?
-
如果您只是学习 OpenMP,那么您显然需要了解
private和shared。i、rowmask、dia1和dia2应该是private。因为i是一个迭代器,所以无论如何它都是私有的。在竞态条件下,您将rowmaks、dia1和dia2设置为零,然后将它们传递给一个使它们成为私有的函数,因此最终一切正常,这主要是偶然的。
标签: parallel-processing openmp