gcc編譯優化簡介:函數
不開優化選項,編譯器將以減小編譯消耗爲目的,而且使debug產生預期的結果。oop
各個語句都是獨立的。若是在某個語句前打上斷點,你能夠爲任意變量賦一個新值,或者改變pc寄存器的值使之指向任意語句。最終得出源碼相應的指望的結果。性能
打開優化選項,編譯器會以犧牲編譯時間和debug能力爲代價,來試圖改善性能和代碼量。fetch
編譯器基於對程序的瞭解來進行優化。一次編譯多個文件到一個輸出文件,編譯器能夠拿到全部這些文件中的信息,在編譯每一個文件時使用。優化
不是全部的優化都直接由某一個選項控制。只有列出來的部分能夠。this
大多優化只是在命令行開啓某個-O等級的時候被enable,不然就是disabled,即便單獨打開,仍是以-O等級爲準。編碼
基於target和gcc的配置,每一個-O等級的優化集會與列表有細微區別。能夠經過gcc –Q –help=optimizers來查看具體的每一個level的精確優化集。spa
gcc -Q –O1 --help=optimizers命令行
gcc -Q -O2 --help=optimizersdebug
能夠看到每一個-O level的優化選項的開關狀況。
優化程度圖示:
-O0
default,減小編譯時間,使得調試產生預期結果。
幾乎不被使用。
-O1
-O即-O1。-O的default。
編譯優化須要更多的時間,對大型函數來講也須要更多內存。
使用-O1, 編譯器嘗試減小代碼大小和執行時間, 而不執行任何須要大量編譯時間的優化。Optimizing compilation takes somewhat more time, and a lot more memory for a large function. With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O2
比-O1更加優化,gcc將執行幾乎全部的不涉及到空間-速度權衡的優化點。優化時間增長,同時目標編碼的性能獲得提高。在O1的基礎上加上更多優化開關。
Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to -O, this option increases both compilation time and the performance of the generated code.
-O3
比O2更加優化。在O2的優化點上,再加上以下優化點:
Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the
-finline-functions, -funswitch-loops, -fpredictive-commoning, -fgcse-after-reload, -ftree-vectorize, -fvect-cost-model, -ftree-partial-pre and -fipa-cp-clone options
-Os
優化size。執行
1. 全部O2級別中,不會增大code size的優化點。
2. 更多用來減少code size的優化點。
Optimize for size. -Os enables all -O2 optimizations that do not typically increase code size. It also performs further optimizations designed to reduce code size. -Os disables the following optimization flags: -falign-functions -falign-jumps -falign-loops -falign-labels -freorder-blocks -freorder-blocks-and-partition -fprefetch-loop-arrays -ftree-vect-loop-version
-Ofast
無視嚴格的標準合規性。執行:
1. 全部O3的優化集。
2. 一些不符合嚴格規定的優化點。
Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs.
It turns on -ffast-math and the Fortran-specific -fno-protect-parens and -fstack-arrays.
-Og
優化debug體驗。
1. 全部不會搞亂debug的優化點。
是在 edit-compile-debug週期應該選用的Opt level。提供一個能夠保持快速編譯和良好debug體驗的優化等級。
Optimize debugging experience. -Og enables optimizations that do not interfere with debugging. It should be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience.
gcc-manual:
1.Linux: man gcc
2.download from https://gcc.gnu.org/onlinedocs/