gpt4 book ai didi

c - gcc -O3 如何使运行速度如此之快?

转载 作者:太空狗 更新时间:2023-10-29 15:46:35 27 4
gpt4 key购买 nike

设 test_speed.c 为以下 C 代码:

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

我在终端运行:

gcc -o test_speed test_speed.c 

然后:

time ./test_speed

我得到:

enter image description here

现在我运行以下命令:

gcc -O3 -o test_speed test_speed.c

然后:

time ./test_speed

我得到:

enter image description here

第二次跑怎么能这么快?它在编译过程中已经计算出来了吗?

最佳答案

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

for(i=0; i < 1000000000; i++) {}

没有副作用(i 的值除外)并完全删除循环(直接将 i 设置为 1000000000)。

反汇编(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

如您所见,该优化级别不适合校准的事件 CPU 循环(结果与 -O2 相同,但循环仍未优化,只有 -O)

关于c - gcc -O3 如何使运行速度如此之快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49633618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com