|
、if...else...语句的优化
(一)
1、源代码:
if (sub(ltpg, LTP_GAIN_THR1) <= 0)//ltpgLTP_GAIN_THR1,则adapt=1
{
adapt = 0;
}
else
{
if (sub(ltpg, LTP_GAIN_THR2) <= 0)
{
adapt = 1;
}
}
else
{
adapt = 2;
}
2、改编后的代码:
adapt = (ltpg > LTP_GAIN_THR1) + (ltpg > LTP_GAIN_THR2);
(二)
1、源代码:
if (adapt == 0)
{
if (filt > 5443)
{
result = 0;
}
else
{
if (filt < 0)
{
result = 16384;
}
else
{
filt = _sshl(filt, 18) >> 16; // Q15
result = _ssub(16384, _smpy(24660, filt) >> 16);
}
}
}
else
{
result = 0;
}
2、改编后的代码:
filt1 = _sshl(filt, 18) >> 16;
tmp = _smpy(24660, filt1) >> 16;
result = _ssub(16384, tmp * (filt >= 0));//filt<0则result = 16384;
result = result * (!((adapt != 0) || (filt > 5443)));//最巧妙的是,将if...else...融入表达式,adapt!=0和filt>5443任意一个条件成立result就等于0
(三)
1、源代码:
static Word16 saturate(Word32 L_var1)
{
Word16 swOut;
if (L_var1 > SW_MAX)
{
swOut = SW_MAX;
giOverflow = 1;
}
else if (L_var1 < SW_MIN)
{
swOut = SW_MIN;
giOverflow = 1;
}
else
swOut = (Word16)L_var1; /* automatic type conversion */
return (swOut);
}
2、改编后的代码:
static inline Word32 L_shl(Word32 a, Word16 b)
{
return ((Word32)((b) < 0 ? (Word32)(a) >> (-(b)) : _sshl((a), (b))));
}
3、优化方法说明:
如果在循环中出现if...else...语句,由于if...else...语句中有跳转指令,而每个跳转指令有5个延迟间隙,因此程序执行时间延长;另外,循环内跳转也使软件流水受到阻塞。直接使用逻辑判断语句可以去除不必要的跳转。例如在例1的源代码最多有两次跳转,而改编后不存在跳转。例2和例3同样也去掉了跳转。
技巧:
尽可能地用逻辑判断语句替代if...else...语句,减少跳转语句。
|
|