嚴重的是,剛剛離開,最多的編譯器。我已經看到了海灣合作委員會在其「瘋狂的」-O3
水平上輸出的代碼,這證明了編寫這些優化引擎的人不是外星人,就是來自遙遠未來的時間。
我還沒有看到register
或inline
在我的代碼的性能有明顯的差異。這並不意味着不會,只是編譯器在處理器中提取最後一盎司的性能時比我們知道更多的技巧。
只要優化進行,它應該只在存在真正問題的地方完成。這意味着分析代碼並發現瓶頸,但更重要的是,不會優化在上下文中不被視爲緩慢的操作。對於用戶而言,一次操作是否需要十分之一秒或百分之一的零差異。
有時,優化可讀性是你可以做:-)
順便說一句,這只是一個的漂亮的花樣gcc在你的最好的之一。考慮下面的代碼應該計算階乘並返回它:
static int fact (unsigned int n) {
if (n == 0) return 1;
return n * fact (n-1);
}
int main (void) {
return fact (6);
}
這編譯爲(以-O3
):
main: pushl %ebp ; stack frame setup.
movl $720, %eax ; just load 720 (6!) into eax.
movl %esp, %ebp ; stack frame
popl %ebp ; tear-down.
ret ; and return.
這是正確的,GCC只是工作這一切在編譯時和原來整個事情到相當於:
int main (void) { return 720; }
對比這與-O0
(天真)版本:
main: pushl %ebp ; stack
movl %esp, %ebp ; frame
andl $-16, %esp ; set
subl $16, %esp ; up.
movl $6, (%esp) ; pass 6 as parameter.
call fact ; call factorial function.
leave ; stack frame tear down.
ret ; and exit.
fact: pushl %ebp ; stack
movl %esp, %ebp ; frame
subl $24, %esp ; set up.
cmpl $0, 8(%ebp) ; passed param zero?
jne .L2 ; no, keep going.
movl $1, %eax ; yes, set return to 1.
jmp .L3 ; goto return bit.
.L2: movl 8(%ebp), %eax ; get parameter.
subl $1, %eax ; decrement.
movl %eax, (%esp) ; pass that value to next level down.
call fact ; call factorial function.
imull 8(%ebp), %eax ; multiply return value by passed param.
.L3: leave ; stack frame tear down.
ret ; and exit.
編譯器也是人! :-)如果您的代碼易於閱讀和理解,他們會看到您的意圖併爲此生成代碼。如果你做了一些以前從未見過的「聰明伎倆」,你的同事和編譯器都不知道該怎麼做。 – 2011-03-29 05:10:16