我试过这个,但我不知道它是否正确,并且计算执行时间有时它会给我 0
在代码中。
我首先创建了一个结构来存储要插值的点的所有坐标我有一个要插值的点表,所以我使用了pragma parallel for
执行 for 部分以插入所有点。变量 R1、R2 和 P 是 double 变量,并且在线程之间共享。
#pragma omp parallel for
for(i=0;i<N ; i++)
{
R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
P = BilinearInterpolation(Table[i].y1, R1, Table[i].y2, R2, Table[i].y);
TableInter[i] = P;
}
最佳答案
#pragma omp parallel for
for(i=0;i<N ; i++)
{
R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
P = BilinearInterpolation(Table[i].y1, R1, Table[i].y2, R2, Table[i].y);
TableInter[i] = P;
}
您的代码的问题是 R1
, R2
, 和 P
由多个线程共享和更新,因此您有竞争条件。例如,一个线程可能正在更改 P
而另一个添加 P
到TableInter[i]
.尽管如此,您可以通过将这些变量声明为私有(private)变量(即在并行区域内声明它们)或使用 OpenMP 的 private
轻松解决这种竞争条件。子句(#pragma omp parallel for private(R1, R2, P
)。 #pragma omp parallel for private(R1, R2)
for(i=0;i<N ; i++)
{
R1 = BilinearInterpolation(Table[i].x1, Table[i].Q11,Table[i].x2, Table[i].Q21,Table[i].x);
R2 = BilinearInterpolation(Table[i].x1, Table[i].Q12, Table[i].x2, Table[i].Q22,Table[i].x);
TableInter[i] = BilinearInterpolation(Table[i].y1, R1, Table[i].y2, R2, Table[i].y);
}
只要BilinearInterpolation
方法不会修改线程之间的共享状态,此代码是无竞争条件的。calculate the time of execution sometimes it gives me 0 in the code,
要计算时间,可以使用 OpenMP 函数 omp_get_wtime , 如下:
double start = omp_get_wtime();
// the code that you want to measure.
double end = omp_get_wtime();
printf("%f\n",end-start);
关于c++ - 如何进行并行双线性插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65595876/