以下哪一种技术是整数除2的最佳选择,为什么?

技巧1:

x = x >> 1;

技巧2:

x = x / 2;

这里x是整数。


当前回答

查看编译器的输出来帮助您做出决定。我在x86-64上使用 gcc (gcc) 4.2.1 20070719 [FreeBSD]

也可以在godbolt上看到编译器的在线输出。

What you see is the compiler does use a sarl (arithmetic right-shift) instruction in both cases, so it does recognize the similarity between the two expressions. If you use the divide, the compiler also needs to adjust for negative numbers. To do that it shifts the sign bit down to the lowest order bit, and adds that to the result. This fixes the off-by-one issue when shifting negative numbers, compared to what a divide would do. Since the divide case does 2 shifts, while the explicit shift case only does one, we can now explain some of the performance differences measured by other answers here.

C代码与汇编输出:

对于除法,你的输入是

int div2signed(int a) {
  return a / 2;
}

这个编译成

    movl    %edi, %eax
    shrl    $31, %eax            # (unsigned)x >> 31
    addl    %edi, %eax           # tmp = x + (x<0)
    sarl    %eax                 # (x + 0 or 1) >> 1  arithmetic right shift
    ret

shift也是一样

int shr2signed(int a) {
  return a >> 1;
}

输出:

    sarl    %edi
    movl    %edi, %eax
    ret

其他isa即使不能做得更好,也能同样有效地做到这一点。例如GCC For AArch64使用:

        add     w0, w0, w0, lsr 31      // x += (unsigned)x>>31
        asr     w0, w0, 1               // x >>= 1
        ret

其他回答

哪一个是最好的选择,为什么整数除以2?

这取决于你对最佳的定义。

如果你想让你的同事讨厌你,或者让你的代码难以阅读,我肯定会选择第一个选择。

如果你想把一个数除以2,就用第二个数。

这两者是不等价的,如果数字是负的或在更大的表达式中,它们的行为是不一样的——bitshift的优先级比+或-低,除法的优先级更高。

您应该编写代码来表达其意图。如果您关心的是性能,不要担心,优化器在这类微优化方面做得很好。

让你的意图更清楚……例如,如果你想除法,使用x / 2,并让编译器将其优化为shift运算符(或其他任何运算符)。

今天的处理器不会让这些优化对程序的性能产生任何影响。

使用最能描述您要做的事情的操作。

如果你将数字作为一个比特序列来处理,请使用bitshift。 如果你把它当作一个数值,使用除法。

请注意,它们并不完全相等。对于负整数,它们可以给出不同的结果。例如:

-5 / 2  = -2
-5 >> 1 = -3

(ideone)

使用x = x / 2;或x /= 2;因为将来有可能会有一个新的程序员使用它。因此,他更容易发现代码行中发生了什么。每个人可能都不知道这种优化。

Mod 2, test for = 1。不知道c中的语法,但这可能是最快的。