Differences

This shows you the differences between two versions of the page.

Link to this comparison view

programming:c-cpp-performance [2006/12/14 13:23]
cyril created
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) 
-</code> 
- 
-But be careful, macros are very dangerous. For example parenthesis around ''x'' are not optional at all. Indeed macros are stupidly replaced before compilation, and ''x*x'' called with ''a-b'' will be replaced by ''a-b*a-b'' which is not what you want ! 
- 
-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:instruction-timings]]) and none of these traps. That's why in C++ you MUST use inline functions instead of macros.  
- 
-You can even use templates to have a generic function : 
-<code cpp> 
-<template typename T> 
-inline T sqr(T x) { return x*x; } 
-</code> 
- 
-And use it like : 
-<code cpp> 
-int x = 5; 
-int y = sqr<int>(x); 
-</code> 
- 
-== 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; 
- public: 
-  int getX() { return x; } // this function is automatically inlined ! 
-  int getY() { return y; } // this function is automatically inlined ! 
-} 
-</code> 
- 
- 
-===== Instruction timings ===== 
- 
-You can see complete results [[programming:instruction-timings|here]]. 
- 
-===== 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, just compile in Release mode instead of Debug mode. 
- 
-For gcc/g++ don't use ''-g'' option, and use ''-O1'', ''-O2'' or ''-O3'' optimization flag (increasing optimization). 
programming/c-cpp-performance.txt ยท Last modified: 2013/09/19 16:40 (external edit)
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0