不回答這個問題,但舉了一個編譯時優化的例子。當被要求時,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