要关注程序运行效率的时候,会使用到内联函数。

  • Stack operations and jumps are needed for a function call.
  • It is a heavy cost for some frequently called tiny functions.

函数的调用是有代价的,尤其是简单的函数被频繁调用。
image.png
Use the inline function, The generated instructions by a compiler can be as follows to improve efficiency

伪代码:

  1. int main()
  2. {
  3. int num1 = 20;
  4. int num2 = 30;
  5. int maxv =
  6. {
  7. if (num1 > num2)
  8. return num1;
  9. else
  10. return num2;
  11. }
  12. maxv =
  13. {
  14. if (numn > maxv)
  15. return numn;
  16. else
  17. return maxv;
  18. }
  19. }

内联函数可能会把整个函数体挪到函数调用的地方,就不需要函数调用,函数调用的代价就不需要了。
缺点:
编译好的指令中会有很多重复代码,使得编译产生的机器代码文件扩大,这是典型的空间换时间的思想应用。

在函数前加上inline,就会成为内联函数,但是:inline suggests the compiler to perform that kind of optimizations. :::warning 只是给编译器建议要以inline编译该函数。 ::: The compiler may not follow your suggestion if the function is too complex or contains some constrains.
Some functions without inline may be optimized as an inline one.

  1. inline float max_function(float a, float b)
  2. {
  3. if (a > b)
  4. return a;
  5. else
  6. return b;
  7. }

Why not use a macros? 宏

  1. #define MAX_MACRO(a, b) (a)>(b) ? (a) : (b)

宏属于预处理,在程序编译之前,做文本替换,也就没有了函数调用的代价了。

  • The source code will be replaced by a preprocessor.
  • Surely no cost of a function call,
  • And a, b can be any types which can compare. ```cpp

    include

    using namespace std;

//#define MAX_MACRO(a, b) a>b ? a : b

define MAX_MACRO(a, b) (a)>(b) ? (a) : (b)

int main() { int num1 = 20; int num2 = 30; int maxv = max_function(num1, num2); cout << maxv << endl;

  1. maxv = MAX_MACRO(num1, num2);
  2. cout << maxv << endl;
  3. maxv = MAX_MACRO(num1++, num2++);
  4. cout << maxv << endl;
  5. cout << "num1=" << num1 << endl;
  6. cout << "num2=" << num2 << endl;
  7. num1 = 0xAB09;
  8. num2 = 0xEF08;
  9. // 打开第4hang代码,测试使用宏时不加括号的效果,最好加括号
  10. // &位运算的优先级小于`>` 。
  11. maxv = MAX_MACRO(num1&0xFF, num2&0xFF); // 只保留最低位的字节,只保留09
  12. cout << maxv << endl;
  13. return 0;

}

// 30 // 30 // 31 // num1=21 // num2=32 // 9 `` maxv = MAX_MACRO(num1++, num2++);->maxv = (num1++) > (num2++) ? (num1++): (num2++);`

  1. num1=20 > num2 is False
  2. num1 ++ -> 21 and num2++ => 31
  3. maxv = num2 = 31
  4. num2 ++ -> 32

所以使用宏的话,虽然不用考虑函数调用,但是一旦考虑不周,就会造成coder认知之外的错误。

Inline in OpenCV
image.png
image.png
OpenCV中根据平台不同,会有不同的inline的宏定义操作。