C语言 在 openMP 程序中嵌套 for 循环需要太长时间



我在使用 openMP 并行化我的程序时遇到问题。第一个 for 循环大约需要 10 毫秒,但第二个循环大约需要 45 秒。我不确定我是否只是在循环中做错了什么,浪费时间。

float A[M][M];
float B[M][M];
float C[M][M];
main(int argc, char** argv) {
float temp;
float real;
float error = 0;
int i,j,k;
double time_start;
double time_end;
double time_mid;
int n  = 12;
omp_set_num_threads(n);
time_start = omp_get_wtime();

#pragma omp parallel default(shared) private(i,j,k,temp,real) reduction(+:error)
#pragma omp for
for (i=0; i<M; i++) {
for (j=0; j<M; j++) {
A[i][j] = ((i+1)*(j+1))/(float)M;
B[i][j] = (j+1)/(float)(i+1);
}
}
time_mid = omp_get_wtime();
#pragma omp for
for (i=0; i<M; i++) {
for (j=0; j<M; j++) {
temp = 0;
for (k=0; k<M; k++) {
temp += A[i][k]*B[k][j];
}
C[i][j] = temp;
real =(float) (i+1)*(j+1);
error = error + (float) fabs(temp-real)/real;
}
}

time_end = omp_get_wtime();
error = (100/(float)(M*M))*error;
printf("Percent error for C[][] is: %fn", error);
printf("Time is: %fn%fn%fn%fn", time_end-time_start, time_start, time_mid, time_end);
return 0;
}

来自 OpenMP 规范(第 35 页,2.1 指令格式 C/C++https://www.openmp.org/wp-content/uploads/openmp-4.5.pdf

一个 OpenMP 可执行指令最多适用于一个后续指令 语句,它必须是结构化块。

C++中块的定义是stmt.block

因此,#pragma omp parallel default(shared) private(i,j,k,temp,real) reduction(+:error)仅适用于第一个块(您的第一个 for 循环(

其他循环不在"#pragma omp parallel"上下文中。

使用#pragma omp parallel{}包围第二个循环。

最新更新