提高C循环的效率

时间:2017-11-06 17:58:56

标签: c loops optimization

我有一些工作的c代码,我希望提高效率。我知道最好避免循环中的if语句,但是我在这里努力解决这个问题。任何人都可以建议我如何使以下代码更有效率?

for(iy=0;iy<Ny;iy++) {
for(ix=0;ix<Nx;ix++) {


    if (ix==0) {
      pudx = (u[1][iy] + u[Nx-1][iy] - 2.0*u[0][iy])/(calc1);   
    } else if (ix==Nx-1) {
      pudx = (u[0][iy] + u[Nx-2][iy] - 2.0*u[Nx-1][iy])/(calc1);  
    } else {
      pudx = (u[ix+1][iy] + u[ix-1][iy] - 2.0*u[ix][iy])/(calc1);
    }

    if (iy==0) {
      pudy = (u[ix][1] + u[ix][Ny-1] - 2.0*u[ix][0])/(calc2);    
    } else if (iy==Ny-1) {
      pudy = (u[ix][0] + u[ix][Ny-2] - 2.0*u[ix][Ny-1])/(calc2);   
    } else {
      pudy = (u[ix][iy+1] + u[ix][iy-1] - 2.0*u[ix][iy])/(calc2);
    }


    u_new[ix][iy] = 2.0*u[ix][iy] - u_old[ix][iy] + calc*(pudx+pudy);

  }
}

我知道这样的优化可以通过编译器来完成,但我想用-o标志来提高效率(没有编译器优化)。

1 个答案:

答案 0 :(得分:2)

在@JohnBollinger之后:(未经测试,很明显)

unsigned ix, iy;
for(iy=0;iy<Ny;iy++) {
  unsigned  yl,yh;

  yl = (iy -1) %Ny; yh = (iy +1) %Ny;
  for(ix=0;ix<Nx;ix++) {
      unsigned xl,xh;

      xl = (ix -1) %Nx; xh = (ix +1) %Nx;
      yl = (iy -1) %Ny; yh = (iy +1) %Ny;

      pudx = (u[xh][iy] + u[xh][iy] - 2.0*u[ix][iy])/(calc1);   
      pudy = (u[ix][yh] + u[ix][yl] - 2.0*u[ix][iy])/(calc2);    

    u_new[ix][iy] = 2.0*u[ix][iy] - u_old[ix][iy] + calc*(pudx+pudy);

  }
}