以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
以下哪一种技术是整数除2的最佳选择,为什么?
技巧1:
x = x >> 1;
技巧2:
x = x / 2;
这里x是整数。
当前回答
只是加了一个注释
在一些基于vm的语言中,x *= 0.5通常会更快——尤其是actionscript,因为变量不需要被检查是否除以0。
其他回答
就CPU而言,位移运算比除法运算快。 然而,编译器知道这一点,并将适当地优化到它可以的程度, 因此,您可以以最有意义的方式编写代码,并且知道您的代码是有意义的 有效地运行。但是请记住,由于前面指出的原因,在某些情况下,无符号整型可以比整型更好地优化。 如果你不需要符号算术,那么不要包含符号位。
哪一个是最好的选择,为什么整数除以2?
这取决于你对最佳的定义。
如果你想让你的同事讨厌你,或者让你的代码难以阅读,我肯定会选择第一个选择。
如果你想把一个数除以2,就用第二个数。
这两者是不等价的,如果数字是负的或在更大的表达式中,它们的行为是不一样的——bitshift的优先级比+或-低,除法的优先级更高。
您应该编写代码来表达其意图。如果您关心的是性能,不要担心,优化器在这类微优化方面做得很好。
显然,如果你是在为下一个阅读你的代码的人写代码,那么你应该追求“x/2”的清晰度。
然而,如果速度是你的目标,那就两种方法都试一试,把握好时间。几个月前,我做了一个位图卷积例程,它涉及到在一个整数数组中步进,并将每个元素除以2。我做了各种各样的事情来优化它,包括用“x>>1”代替“x/2”的老技巧。
当我计算这两种方式时,我惊奇地发现x/2比x>>1快
这是使用Microsoft VS2008 c++并打开默认优化。
我想说有几件事需要考虑。
Bitshift should be faster, as no special computation is really needed to shift the bits, however as pointed out, there are potential issues with negative numbers. If you are ensured to have positive numbers, and are looking for speed then I would recommend bitshift. The division operator is very easy for humans to read. So if you are looking for code readability, you could use this. Note that the field of compiler optimization has come a long way, so making code easy to read and understand is good practice. Depending on the underlying hardware, operations may have different speeds. Amdal's law is to make the common case fast. So you may have hardware that can perform different operations faster than others. For example, multiplying by 0.5 may be faster than dividing by 2. (Granted you may need to take the floor of the multiplication if you wish to enforce integer division).
如果您追求的是纯粹的性能,我建议您创建一些可以执行数百万次操作的测试。对执行进行多次采样(您的样本量),以确定哪一个在统计上最适合您的操作系统/硬件/编译器/代码。
Knuth说:
过早的优化是万恶之源。
所以我建议用x /= 2;
这样代码很容易理解,而且我认为这种形式的操作优化,对处理器来说不会有太大的区别。