Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        2年前关闭。
                                                                                            
                
        
我有一些希望提高效率的工作C代码。我知道最好避免语句循环,但是我在这里努力解决这个问题。谁能建议我如何使以下代码更有效?

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标志来提高效率(不进行编译器优化)。

最佳答案

@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);

  }
}

关于c - 提高C循环的效率,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47142992/

10-11 15:03