views:

111

answers:

2

I'd like to know which settings should I set so I can get my C++ programs code to be as optimized as possible for speed or size. How can I do that?

Thanks

+1  A: 

You can use following switches of compilation to produce code optimized for speed.

  • /O2
  • /Ot

You can find reference of compiler switches for code optimization here.

Mahin
Yes I am aware of that. But I didn't successfuly put O2 without having to put a whole lot of other options off that then don't allow me to debug the code (which is the object as I want to see it's dissambled code). I tried /Ox, but to use it I had to turn off basic runtime checks(/RTCs), debug information format, and another I don't remember.
devoured elysium
A: 

For the most part, I would say you don't need to worry too much about the switches. The defaults tend to be okay for most purposes. Mahin has pointed out where you can find what all the switches do, but you must be careful because they can have some unintended side-effects.

For example, the gcc compiler (which I am more familiar with) has a switch -fomit-frame-pointer. It is okay to use it. Doing so will free up a register. However, if your program crashes, you will get no stack traces. So, if you are trying to debug your program, you don't want this one. Other optimizations could have "crazier" side-effects depending on your system.

The other thing to point out is that, while the flags generally do what they say they are going to, it's not always guaranteed. For example, (again, in gcc), the /O3 flag should produce "more optimized" code. This isn't always the case however, and it's recommended to stick with /O2.

JasCav
I've been learning assembly and I've been checking non-optimized code. A function that only returns 5, with no arguments, only needs 2 lines of code with assembly, mov eax, 5; retn;, although from the code I see coming from c++, it takes like 20 instructions, he pushes arguments onto stack, etc. I'd like to see what he does if he tries to optimize.
devoured elysium