【发布时间】:2021-04-04 05:54:51
【问题描述】:
我想使用 OpenMP 来并行化一个 for-loop 计算器,它执行以下操作:
B = (int*)malloc(sizeof(int) * N); //N is known
for(i=0;i<500000;i++)
{
for(j=0;j<M;j++) B[j]=i+j; //M is different from N, but M <= N;
some operations on B which produce a variable L;
printf("%d\n",L);
}
我不需要重新分配 B,因为它将为每次迭代相应地定义其值。这些操作将只使用 B[0] 到 B[M-1]。这样可以节省大量B的分配和初始化时间。
为了使用openmp,我把代码改成这样:
#pragma omp parallel num_threads(32) private(i,j,B,M,L)
{
B = (int*)malloc(sizeof(int) * N); //N is known
#pragma omp parallel for
for(i=0;i<500000;i++)
{
for(j=0;j<M;j++) B[j]=i+j; //M is different from N, but M <= N;
some operations on B which produce a variable L;
printf("%d\n",L);
}
}
与第一个相比,它的运行速度非常慢,因为它为每个线程创建了一个新的 B 数组(所以 500000 次)。 有没有办法使用 openmp 来避免这种情况?
【问题讨论】:
标签: c++ c multithreading performance openmp