Condividi tramite


Optimizing Your Code 

Optimization is the process of fine-tuning executable performance for best performance and smallest code size. Visual C++ provides the following mechanisms for optimizing code:

Improving Program Performance

For details on how good programming practices can improve program performance, see:

About Optimizing Code

Because optimization changes the code created by the compiler, it is best to optimize your code after you have fully tested and debugged it. That way, you can debug code that closely matches your source code and not worry about the effects of optimization. Once you apply optimizations, you should test your code again. Occasionally, code will behave differently when optimizations are applied. In that event, you may need to debug optimized code. Also see Common Problems When Creating a Release Build for more information.

Optimized code sometimes gives different answers not because of an error but because optimization changes the order of calculations, resulting in slightly different results due to the limits of floating-point precision.

You may also notice some additional warning messages when you compile your code with optimization. This is normal behavior because some warnings relate only to optimized code. If you pay attention to these warnings, you can avoid most of the problems associated with optimization.

Paradoxically, optimizing a program for speed can sometimes cause code to run slower because some optimizations for speed increase code size. Inlining functions, for example, eliminates the overhead of function calls, but inlining too much code may make your program so large that the number of virtual-memory page faults increases. Therefore, the speed gained from eliminating function calls may be lost to memory swapping. For this reason, it is a good idea to measure the performance of your program before and after you apply optimizations. For general guidelines on how best to optimize your application, see Optimization Best Practices.

The optimize Pragma

If a section of your code causes errors or slowdown due to optimization, you can use the optimize pragma to turn off optimization for that section. Enclose the code between two pragmas, like this:

#pragma optimize("", off)
// some code here 
#pragma optimize("", on)

Additional Topics

For additional topics on optimization, see:

See Also

Other Resources

C/C++ Building Reference