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

技巧1:

x = x >> 1;

技巧2:

x = x / 2;

这里x是整数。


当前回答

就CPU而言,位移运算比除法运算快。 然而,编译器知道这一点,并将适当地优化到它可以的程度, 因此,您可以以最有意义的方式编写代码,并且知道您的代码是有意义的 有效地运行。但是请记住,由于前面指出的原因,在某些情况下,无符号整型可以比整型更好地优化。 如果你不需要符号算术,那么不要包含符号位。

其他回答

查看编译器的输出来帮助您做出决定。我在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

使用除法(/),假设这样更清楚。编译器将相应地进行优化。

就CPU而言,位移运算比除法运算快。 然而,编译器知道这一点,并将适当地优化到它可以的程度, 因此,您可以以最有意义的方式编写代码,并且知道您的代码是有意义的 有效地运行。但是请记住,由于前面指出的原因,在某些情况下,无符号整型可以比整型更好地优化。 如果你不需要符号算术,那么不要包含符号位。

第一个看起来像除法吗?不。如果你想除法,用x / 2。如果可能的话,编译器可以优化它使用位移位(它被称为强度减少),这使得它成为一个无用的微优化,如果你自己做它。

我同意其他答案,你应该支持x / 2,因为它的意图更清楚,编译器应该为你优化它。

然而,选择x / 2而不是x >> 1的另一个原因是,如果x是一个有符号int并且是负的,那么>>的行为是依赖于实现的。

ISO C99标准第6.5.7节第5项:

E1 >> E2的结果是E1位右移E2位位置。如果E1 无符号类型,或者E1有符号类型且值为非负值, 结果值为E1 /商的积分部分 2 e2。如果E1具有符号类型和负值,则结果值为 是由实现定义的。