提高C循环的效率 [英] Improving efficiency of a C loop
本文介绍了提高C循环的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些可以提高效率的有效C代码.我知道最好避免语句循环,但是我在这里努力解决这个问题.谁能建议我如何使以下代码更有效?
I have some working c code that I am looking to make more efficient. I know that it is best to avoid if statements in loops however I am struggling to get around this here. Can anyone suggest how I could make the following code more efficient?
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标志(不进行编译器优化)来提高效率.
I am aware that such optimization can be done with a compiler but I would like to improve the efficiency with the -o flag (no compiler optimization).
推荐答案
在@JohnBollinger之后:(显然是未经测试的)
After @JohnBollinger: (untested, obviously)
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循环的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文