问题描述
我正在尝试使用 #pragma omp simd 对嵌套循环进行矢量化,但内部循环减少了。有没有办法做到这一点?
#pragma omp simd collapse(2) reduction(+:total[i])
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
float distance = sqrt(
(x[i][0]-x[j][0]) * (x[i][0]-x[j][0]) +
(x[i][1]-x[j][1]) * (x[i][1]-x[j][1]) +
(x[i][2]-x[j][2]) * (x[i][2]-x[j][2])
);
total[i] += distance;
}
}
目前,它只是在编译时出现此错误:
error: identifier "i" is undefined
#pragma omp simd collapse(2) reduction(+:total[i])
^
解决方法
您不能将变量 'i' 传递给 +:total[i]
,无论是指定要缩减的数组子节还是仅执行 +:total
。但是请记住,您需要一个支持 OpenMP 4.5 数组缩减功能的编译器。
#pragma omp simd collapse(2) reduction(+:total)
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
float distance = sqrt(
(x[i][0]-x[j][0]) * (x[i][0]-x[j][0]) +
(x[i][1]-x[j][1]) * (x[i][1]-x[j][1]) +
(x[i][2]-x[j][2]) * (x[i][2]-x[j][2])
);
total[i] += distance;
}
}
当编译器不支持 OpenMP 4.5 数组缩减功能时,可以选择显式实现缩减 (check this SO thread to see how)。