不回答这个问题,但举了一个编译时优化的例子。当被要求时,gcc优化了代码。 -O(优化)选项使不同级别的优化成为可能。它可以用作-O1,-O2和-O3。 gcc手册页精确地描述了每个级别的含义。
-S选项将C转换为汇编并保存在.s文件中。
test.c的
#include <stdio.h>
int abc;//Global variable
void main()
{
abc = 3;
if(abc == 3)
printf("abc will be always 3");
else
printf("This will never executed");
}
Whitout gcc的优化这两个字符串出现在汇编代码。
$ GCC -S test.c的;猫test.s
.file "test.c"
.comm abc,4,4
.section .rodata
.LC0:
.string "abc will be always 3"
.LC1:
.string "This will never executed"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $3, abc(%rip)
movl abc(%rip), %eax
cmpl $3, %eax
jne .L2
movl $.LC0, %eax
movq %rax, %rdi
movl $0, %eax
call printf
jmp .L1
.L2:
movl $.LC1, %eax
movq %rax, %rdi
movl $0, %eax
call printf
.L1:
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.6.1 20110908 (Red Hat 4.6.1-9)"
.section .note.GNU-stack,"",@progbits
维特GCC级1优化只有一个字符串被转换成装配
$ GCC -O1 -S测试。 c; cat test.s
.file "test.c"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "abc will be always 3"
.text
.globl main
.type main, @function
main:
.LFB11:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $3, abc(%rip)
movl $.LC0, %edi
movl $0, %eax
call printf
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE11:
.size main, .-main
.comm abc,4,4
.ident "GCC: (GNU) 4.6.1 20110908 (Red Hat 4.6.1-9)"
.section .note.GNU-stack,"",@progbits
在C中最接近运行时优化的是基于Profiler的优化。您编译该程序,然后运行它,同时使用分析器收集统计信息。然后再次编译,将这些统计数据提供给编译器。第二个编译将使用这些信息来生成更快的代码。 – ugoren 2012-02-04 17:00:18