测试移位和乘除的比较,发现移位比乘除运算快一个位数的速度,但是难点在于判断是否是2的幂次级的数,如果不是还得通过代码拆分到2的幂次+上分子的累和,然后通过移位得到2的次幂数这样;
下列代码只是简单的判断是幂级数则移位运算,不是则正常计算,不是完全都是移位算,(之后如果找到方法判断更快在更新)
C/C++:
#include <iostream> uint64_t Multiply_Dived(uint64_t member, uint64_t denominator, char style)
{
//判断分母是否是2的次幂
if (denominator & (denominator - ))
{
if (style == '*')
{
while ((denominator >>= ) != )
{
member <<= ;
} } else
{
while ((denominator >>= ) != )
{
member >>= ;
} }
return member;
} if (style == '*')
{
return member * denominator;
} else
{
return member / denominator;
}
} uint64_t Nomorl(uint64_t member, uint64_t denominator, char style)
{
if (style == '*')
{
return member * denominator;
} else
{
return member / denominator;
}
} int main()
{
std::clock_t start = , stop = ;
start = clock();
for (uint64_t i = ; i < ; i++)
{
Multiply_Dived(, , '/');
}
stop = clock();
std::cout << "除移位运行时间: " << ((double) (stop - start) / CLOCKS_PER_SEC) << std::endl; start = clock();
for (uint64_t i = ; i < ; i++)
{
Nomorl(, , '/');
}
stop = clock();
std::cout << "正常除运行时间: " << ((double) (stop - start) / CLOCKS_PER_SEC) << std::endl; return ;
}