这是一位高级经理在面试时问的问题。

哪个更快?

while(1) {
    // Some code
}

or

while(2) {
    //Some code
}

我说过两者具有相同的执行速度,因为while中的表达式最终应求值为true或false。在这种情况下,两者都求值为true,并且while条件中没有额外的条件指令。因此,两者将具有相同的执行速度,我更喜欢while(1)。

但面试官自信地说: “检查你的基本知识。While(1)比While(2)快。” (他不是在试探我的信心)

这是真的吗?

请参见:“for(;;)”是否比“while (TRUE)”快?如果不是,人们为什么要使用它?


当前回答

它们是相等的。

根据规范,任何不为0的都被认为是真的,所以即使没有任何优化,一个好的编译器也不会生成任何代码 For while(1) or while(2)。编译器将生成一个简单的检查!= 0。

其他回答

显而易见的答案是:正如所发布的,两个片段将运行一个同样繁忙的无限循环,这使得程序无限慢。

虽然从技术上讲,将C关键字重新定义为宏将具有未定义的行为,但这是我能想到的使任何一个代码片段快速的唯一方法:你可以在两个片段之上添加这一行:

#define while(x) sleep(x);

它确实会使while(1)比while(2)快一倍(或慢一半)。

我认为线索可以从“高级经理的询问”中找到。这个人显然在成为经理后就停止了编程,然后他/她花了几年时间才成为高级经理。从未失去对编程的兴趣,但从那以后再也没有写过一行字。所以他提到的并不是“任何一个像样的编译器”,而是“这个人在二三十年前合作过的编译器”。

At that time, programmers spent a considerable percentage of their time trying out various methods for making their code faster and more efficient as CPU time of 'the central minicomputer' was so valueable. As did people writing compilers. I'm guessing that the one-and-only compiler his company made available at that time optimized on the basis of 'frequently encountered statements that can be optimized' and took a bit of a shortcut when encountering a while(1) and evaluated everything else, including a while(2). Having had such an experience could explain his position and his confidence in it.

让你被录用的最好方法可能是,在你顺利地引导他进入下一个面试主题之前,让高级经理忘乎所以地给你讲2-3分钟“编程的美好时光”。(好的时机在这里很重要——太快你会打断故事——太慢你会被贴上焦点不集中的标签)。一定要在面试结束时告诉他,你对这个话题非常感兴趣。

也许面试官是故意问这个愚蠢的问题,想让你回答3点:

基本的推理。这两个循环都是无限的,很难谈论性能。 关于优化级别的知识。他想听听你的意见,如果你让编译器为你做任何优化,它会优化条件,特别是如果块不是空的。 了解微处理器架构。大多数架构都有一个特殊的CPU指令用于与0进行比较(但不一定更快)。

这两个循环都是无限的,但我们可以看到哪个循环每次迭代需要更多的指令/资源。

使用gcc,我编译了以下两个程序,以不同的优化级别进行汇编:

int main(void) {
    while(1) {}
    return 0;
}

int main(void) {
    while(2) {}
    return 0;
}

即使没有优化(-O0),两个程序生成的程序集也是相同的。因此,两个循环之间没有速度差异。

作为参考,下面是生成的程序集(使用gcc main.c -S -masm=intel并带有优化标志):

o0:

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    push    rbp
    .seh_pushreg    rbp
    mov rbp, rsp
    .seh_setframe   rbp, 0
    sub rsp, 32
    .seh_stackalloc 32
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

o1群:

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    sub rsp, 40
    .seh_stackalloc 40
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

-O2和-O3(相同输出):

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .section    .text.startup,"x"
    .p2align 4,,15
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    sub rsp, 40
    .seh_stackalloc 40
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

事实上,为循环生成的程序集对于每个级别的优化都是相同的:

 .L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

重要的部分是:

.L2:
    jmp .L2

我不太懂汇编,但这显然是一个无条件循环。jmp指令无条件地将程序重置回. l2标签,甚至不将值与true进行比较,当然,它会立即再次这样做,直到程序以某种方式结束。这直接对应于C/ c++代码:

L2:
    goto L2;

编辑:

有趣的是,即使没有优化,下面的循环都在汇编中产生完全相同的输出(无条件jmp):

while(42) {}

while(1==1) {}

while(2==2) {}

while(4<7) {}

while(3==3 && 4==4) {}

while(8-9 < 0) {}

while(4.3 * 3e4 >= 2 << 6) {}

while(-0.1 + 02) {}

甚至令我惊讶的是:

#include<math.h>

while(sqrt(7)) {}

while(hypot(3,4)) {}

对于用户定义函数,事情变得更加有趣:

int x(void) {
    return 1;
}

while(x()) {}

#include<math.h>

double x(void) {
    return sqrt(7);
}

while(x()) {}

At -O0, these two examples actually call x and perform a comparison for each iteration.

First example (returning 1):

.L4:
    call    x
    testl   %eax, %eax
    jne .L4
    movl    $0, %eax
    addq    $32, %rsp
    popq    %rbp
    ret
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

Second example (returning sqrt(7)):

.L4:
    call    x
    xorpd   %xmm1, %xmm1
    ucomisd %xmm1, %xmm0
    jp  .L4
    xorpd   %xmm1, %xmm1
    ucomisd %xmm1, %xmm0
    jne .L4
    movl    $0, %eax
    addq    $32, %rsp
    popq    %rbp
    ret
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

However, at -O1 and above, they both produce the same assembly as the previous examples (an unconditional jmp back to the preceding label).

TL;DR

Under GCC, the different loops are compiled to identical assembly. The compiler evaluates the constant values and doesn't bother performing any actual comparison.

The moral of the story is:

  • There exists a layer of translation between C source code and CPU instructions, and this layer has important implications for performance.
  • Therefore, performance cannot be evaluated by only looking at source code.
  • The compiler should be smart enough to optimize such trivial cases. Programmers should not waste their time thinking about them in the vast majority of cases.

这里有一个问题:如果您实际编写一个程序并测量它的速度,两个循环的速度可能是不同的!以下是一些合理的比较:

unsigned long i = 0;
while (1) { if (++i == 1000000000) break; }

unsigned long i = 0;
while (2) { if (++i == 1000000000) break; }

添加了一些打印时间的代码后,一些随机的效果(比如循环在一条或两条缓存线中的位置)可能会产生影响。一个循环可能完全位于一条缓存线内,或者位于一条缓存线的开头,或者它可能横跨两条缓存线。因此,面试官说最快的可能真的是最快的——纯属巧合。

最坏的情况:优化编译器不知道循环做了什么,但知道执行第二个循环时产生的值与第一个循环产生的值相同。并为第一个循环生成完整代码,但不为第二个循环生成完整代码。