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:
- Pragmas and keywords you can insert into your source code.
- Compiler options that support optimizations; see Compiler Options by Category.
Improving Program Performance
For details on how good programming practices can improve program performance, see:
- Tips for Improving Time-Critical Code
- Microsoft Visual Studio and Windows 2000 Scalability Center (http://msdn.microsoft.com/vstudio/centers/scale/default.asp)
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.
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)
For additional topics on optimization, see:
- Compiler Throughput
- Using Function Name Without () Produces No Code
- Optimizing Inline Assembly
- Specifying Compiler Optimization for an ATL Project
- What optimization techniques should I use to improve the client application's performance when loading?
- Optimizing DLL Load Time Performance
- Bugslayer: Improving Runtime Performance with the Smooth Working Set Tool (Part 1) and (Part 2)