[C/C++] GCC/MinGW Optimization

  • GCC/MinGW Optimization
  • 一個程式運作的快慢除了取決於系統的硬體環境、演算法設計之外,程式的最佳化也是一個重要的課題,大部分的人常常會忽略掉編譯器的最佳化部份,導致整個程式一經編譯後效能極慢。一個標準的編譯流程如下:

    Source Code->Preprocessor->Compiler->Assembler->Object Code/Machine Code->Linker->Executables。

    所以在整個編譯過程中,一個很大的環節就發生在Source Code to Assembly Language,一個好的編譯器會幫你將你的原始碼轉成最少行數或者最少Machine Cycle的組合語言,以提昇程式的執行或者記憶空間的效能,反之,則會降低程式的執行效率。GCC/MinGW本身提供了5種等級的最佳化,如下:

    • -O0 or no -O option (default)
    • At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.

    • -O1 or -O
    • This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.

    • -O2
    • This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.

    • -O3
    • This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

    • -Os
    • This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.

    一般來講都用使用-O2 level,得到的效能換比較好,但還是得視你的程式碼的撰寫方向而定。

    Reference:

    http://www.linuxjournal.com/node/7269/print

No comments:

Post a Comment

Orange - data analysis tool

Installation pip install orange3 Run orange python -m Orange.canvas