gcc -O3如何让运行如此之快?

aug*_*lec 3 c gcc

让test_speed.c成为以下C代码:

#include <stdio.h>
int main(){
    int i;
    for(i=0; i < 1000000000; i++) {}
    printf("%d", i);
}
Run Code Online (Sandbox Code Playgroud)

我在终端跑:

gcc -o test_speed test_speed.c 
Run Code Online (Sandbox Code Playgroud)

然后 :

time ./test_speed
Run Code Online (Sandbox Code Playgroud)

我明白了:

在此输入图像描述

现在我运行以下内容:

gcc -O3 -o test_speed test_speed.c
Run Code Online (Sandbox Code Playgroud)

然后 :

time ./test_speed
Run Code Online (Sandbox Code Playgroud)

我明白了:

在此输入图像描述

第二轮怎么能这么快?它是否已在编译期间计算过?

Jea*_*bre 7

这是因为-O3积极的优化假设

for(i=0; i < 1000000000; i++) {}
Run Code Online (Sandbox Code Playgroud)

没有副作用(除了值i)并完全删除循环(直接设置i1000000000).

反汇编(x86):

00000000 <_main>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   83 e4 f0                and    $0xfffffff0,%esp
   6:   83 ec 10                sub    $0x10,%esp
   9:   e8 00 00 00 00          call   e <_main+0xe>
   e:   c7 44 24 04 00 ca 9a    movl   $0x3b9aca00,0x4(%esp)  <== 1000000000 in hex, no loop
  15:   3b
  16:   c7 04 24 00 00 00 00    movl   $0x0,(%esp)
  1d:   e8 00 00 00 00          call   22 <_main+0x22>
  22:   31 c0                   xor    %eax,%eax
  24:   c9                      leave
  25:   c3                      ret
Run Code Online (Sandbox Code Playgroud)

如您所见,优化级别不适合校准的活动CPU循环(结果与之相同-O2,但循环仍然未被优化-O)