Mayank Jain
Mayank Jain

Reputation: 2564

Why C++ compilers have many optimization levels

I was just thinking why C++ compilers have many optimization levels like O1, O2 etc. Why can everything be part of just one optimization level O.

I tried search online a lot but didn't got a convincing answer for this.

Upvotes: 2

Views: 626

Answers (3)

Ripi2
Ripi2

Reputation: 7198

While compilers are smart enough to optimize several common commands (O1) they may try with not-so-frequent strategies (O2) and even with corner cases (O3).

Whether the resulting code is more optimized depends a lot on the original code, and sometimes on the CPU hardware. The only way to tell which "O" is best is trying and measuring running times.

Remember that the one who really knows about the code is you. Write it with part of your brain thinking about how fast it will run.

Upvotes: 1

Hadi Brais
Hadi Brais

Reputation: 23719

For precisely two reasons:

  • There is no one sequence of compiler optimizations that can simultaneously optimize all possible program characteristics of interest, such as execution time, compilation time, code size, energy consumption, binary-portability, etc. In compiler optimizations research, this is known as the phase ordering problem.
  • Most developers do not want to bother with figuring out which compiler optimizations to use and in what order; they just want to use whatever is generally recommended in a small number of common scenarios.

That's why compiler developers have decided to offer a small collection of optimization levels from which developers can easily choose in general, yet offering hundreds of fine-grained optimization options for advanced scenarios.

The term "optimization levels" is really a misnomer, since they are not exactly "levels" with respect to each other. A better term would be something like "optimization groups".

Designing optimization levels is a complicated matter for compilers that target a broad range of programs and architectures, such as GCC, Clang, icc, and VC++. Many research papers have been published in the past decade that show that the optimization levels offered by compilers are far from being the best for a particular program, target architecture, or specific collection thereof. This motivated a line of research on compiler auto-tuning, which can be considered as an approach that falls somewhere in between offering few optimization levels and offering fine-grained control over compiler optimizations.

In summary, optimization levels provide an important convenience for developers, which will be required for many decades to come.

Upvotes: 0

nemequ
nemequ

Reputation: 17492

Off the top of my head: optimizing takes time (more optimization means slower compilation), debugging optimized code can be more difficult, more aggressive optimization can reveal bugs, you can optimize for different things (program size, speed, etc.)…

Upvotes: 4

Related Questions