Differences
This shows you the differences between two versions of the page.
programming:c-cpp-performance [2006/12/14 13:26] cyril |
programming:c-cpp-performance [2013/09/19 16:40] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Performance in C/C++ ====== | ||
- | ===== Inline functions and macros ===== | ||
- | |||
- | Inlining short functions which are often called is very important for performance. | ||
- | |||
- | ==== Macros ==== | ||
- | |||
- | In C you can use macros : | ||
- | <code c> | ||
- | #define sqr(x) (x)*(x) | ||
- | </ | ||
- | |||
- | But be careful, macros are very dangerous. For example parenthesis around '' | ||
- | |||
- | Moreover if the argument of the macro is a function call, this call will be done two times ! | ||
- | |||
- | ==== Inline functions ==== | ||
- | |||
- | With inline functions you have all the advantages (it is as fast as macros, see [[programming: | ||
- | |||
- | You can even use templates to have a generic function : | ||
- | <code cpp> | ||
- | < | ||
- | inline T sqr(T x) { return x*x; } | ||
- | </ | ||
- | |||
- | And use it like : | ||
- | <code cpp> | ||
- | int x = 5; | ||
- | int y = sqr< | ||
- | </ | ||
- | |||
- | == Remark 1 == | ||
- | If you want to export your inline functions in several files, you must define it in the header file. | ||
- | |||
- | == Remark 2 == | ||
- | Methods which are defined inside the body of a class are automatically inlined, eg : | ||
- | <code cpp> | ||
- | class Point | ||
- | { | ||
- | int x,y; | ||
- | | ||
- | int getX() { return x; } // this function is automatically inlined ! | ||
- | int getY() { return y; } // this function is automatically inlined ! | ||
- | } | ||
- | </ | ||
- | |||
- | |||
- | ===== Instruction timings ===== | ||
- | |||
- | You can see complete results [[programming: | ||
- | |||
- | ===== Compiler options ===== | ||
- | |||
- | Using the good optimization options of your compiler for your final release is extremely important. Indeed as long as you compile with debug options no optimization is done, inline functions are not inlined, and overhead is added. | ||
- | |||
- | For VisualStudio, | ||
- | |||
- | For gcc/g++ don't use '' |