# 避免人工循环展开

Fortran 示例（在源代码中执行人工展开）：

m = MOD(N,4)

if ( m /= 0 ) THEN
do i = 1 , m
Dy(i) = Dy(i) + Da*Dx(i)
end do
if ( N < 4 ) RETURN
end if

mp1 = m + 1
do i = mp1 , N , 4
Dy(i) = Dy(i) + Da*Dx(i)
Dy(i+1) = Dy(i+1) + Da*Dx(i+1)
Dy(i+2) = Dy(i+2) + Da*Dx(i+2)
Dy(i+3) = Dy(i+3) + Da*Dx(i+3)
end do

do i=1,N

Dy(i)= = Dy(i) + Da*Dx(i)
end do

C++ 示例（在源代码中执行人工展开）：

double accu1 = 0, accu2 = 0, accu3 = 0, accu4 = 0;

double accu5 = 0, accu6 = 0, accu7 = 0, accu8 = 0;

for (i = 0; i < NUM; i += 8) {
accu1 = src1[i+0]*src2 + accu1;
accu2 = src1[i+1]*src2 + accu2;
accu3 = src1[i+2]*src2 + accu3;
accu4 = src1[i+3]*src2 + accu4;
accu5 = src1[i+4]*src2 + accu5;
accu6 = src1[i+5]*src2 + accu6;
accu7 = src1[i+6]*src2 + accu7;
accu8 = src1[i+7]*src2 + accu8;
}
accu = accu1 + accu2 + accu3 + accu4 +
accu5 + accu6 + accu7 + accu8;

double accu = 0;

for (i = 0; i < NUM; i++ ) {
accu = src1[i]*src2 + accu;
}

Para obter informações mais completas sobre otimizações do compilador, consulte nosso aviso de otimização.