0

I am learning about gcc optimization. As far as I understand the compilers tries to improve/ reduce the code.

That is noticeable when I execute different files with different optimization levels. Adding -O3 during compiling I get the fastest result when I run the compiled program.

As it has been improved, I thought the assembly files must have less commands. However, when looking into that files I saw that it has even more than the default one.

  • Is it true that the assembly file will have more commands, nevertheless it is running faster than the other one? If yes, how is that possible? What has been improved?
  • What is the general influence on assembly / object files when using optimization flags in gcc?
2
  • 2
    The second question is interesting but too broad for Stackoverflow as it's not a simple answerable question that is suitable for the SO format. And the answer to the first question is yes, of course. In fact, trading space for speed is a common computing tradeoff. For starters, read the gcc manual optimsations section which summarises the optimisations options which will or will not affect code size. Commented Dec 22, 2019 at 21:13
  • 1
    @kaylum in fact, most of making a compiler generate good code is about finding the right space/speed tradeoff. Commented Dec 22, 2019 at 21:14

1 Answer 1

3

Compiler optimizations may frequently cause the number of instructions to increase, in order for execution time to decrease. For example, if the compiler sees that a for-loop will always loop exactly N times, it may choose to generate N copies of the loop body, thereby avoiding jump/comparison instructions.

You can tell the compiler to optimize for size (e.g. -Os), in which case it will try really hard not to increase the number of instructions, sometimes at the expense of a slower program. This is very common in embedded applications where the amount of RAM is the most constraining factor.

Running e.g. gcc with -O2 will cause the compiler to try to balance the code to be as fast as possible, while not growing too much in size. Exact how this affects the assembler/object files is very complicated. If you want to know more, there are lots of online courses covering compiler construction and optimizations.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @JesperE Great answer!!
Your first example was great... that's why I accepted your answer. I found exact what your described in my assembly, thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.