Search code examples
c++ccompiler-optimizationcompiler-options

How to set C/C++ compiler options for best optimizations for the CPU in use?


To build binaries with the best optimizations for a specific CPU, how to set C/C++ compiler options? For example, try to utilize CPU features like MMX/3DNow!/SSE/SSE2/SSE3 when the feature is available.


Solution

  • GCC and Clang support -march=native to select the CPU to generate code for from the processor type the compiler is executing on and -mtune=native to optimize code for it. Note that these switches are listed in specific architecture sections, such as the X86 or ARM architectures, so they might not be available for all architectures that the compiler supports.

    Use -march=native if you want to generate code that does not need to execute on other processor models. -march=native implies mtune=native.

    Use -mtune=native without -march=native if you want to generate code tuned for the current processor but that can still execute on the processor models it would be able to otherwise.