This is an old revision of the document!


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 :

#define sqr(x) (x)*(x)

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 because of operators priorities !

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 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 :

<template typename T>
inline T sqr(T x) { return x*x; }

And use it like :

int x = 5;
int y = sqr<int>(x);
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 :

class Point
{
  int x,y;
 public:
  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 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.1166102809.txt.gz · Last modified: 2013/09/19 16:43 (external edit)
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0