在我的代码中,有几种方法包含用于在 ny*nx 矩阵中移动的嵌套循环。我想并行化这个过程,所以我在每种方法上都使用了类似的东西:
#pragma omp parallel for private(jj,x_e,x_w,y_n,y_s)
for(ii=0;ii<ny;ii++) {
for(jj=0;jj<nx;jj++) {
/* determine indices of axis-direction neighbours
** respecting periodic boundary conditions (wrap around) */
y_n = (ii + 1) % ny;
x_e = (jj + 1) % nx;
y_s = (ii == 0) ? (ii + ny - 1) : (ii - 1);
x_w = (jj == 0) ? (jj + nx - 1) : (jj - 1);
//propagate densities to neighbouring cells, following
tmp[ii *nx + jj].speeds[0] = cells[ii*nx + jj].speeds[0]; /* central cell, */
/* no movement */
tmp[ii *nx + x_e].s[1] = cells[ii*nx + jj].s[1]; /* east */
tmp[y_n*nx + jj].s[2] = cells[ii*nx + jj].s[2]; /* north */
tmp[ii *nx + x_w].s[3] = cells[ii*nx + jj].s[3]; /* west */
tmp[y_s*nx + jj].s[4] = cells[ii*nx + jj].s[4]; /* south */
tmp[y_n*nx + x_e].s[5] = cells[ii*nx + jj].s[5]; /* north-east */
tmp[y_n*nx + x_w].s[6] = cells[ii*nx + jj].s[6]; /* north-west */
tmp[y_s*nx + x_w].s[7] = cells[ii*nx + jj].s[7]; /* south-west */
tmp[y_s*nx + x_e].s[8] = cells[ii*nx + jj].s[8]; /* south-east */
}
}
然而,这段代码(以及其他代码)非常慢。有什么方法可以纠正我的#pragma 语句并重写数据结构或循环以使其缓存友好并避免错误共享?
PS:代码是用编译的,-O3
所以每次小的优化尝试都没有达到任何加速。