使用 inline 关键字定义函数
#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono;
inline int minus_ab(int a, int b) {
return a - b;
}
inline int add_ab(int a, int b) {
return a + b;
}
inline int multi_ab(int a, int b) {
return a * b;
}
int main(int argc, char** argv){
auto tick = high_resolution_clock::now();
int x;
int max_kRound = atoi(argv[1]);
int a=1, b=2;
for (int i=0; i<max_kRound*1000; i++) {
x = add_ab(a, b);
x = minus_ab(a, b);
x = multi_ab(a, b);
}
auto tock = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(tock - tick);
cout << "max round= " << max_kRound << "k" << endl;
cout << duration.count() / 1000 << " ms" << endl;
}
真正 inline 的写代码
...
for (int i=0; i<max_kRound*1000; i++) {
x = a+b;
x = a-b;
x = a*b;
}
...
上面两个程序我分别设置循环数为 1e9 ,结果第一个程序大概是第二个的三倍时间。我理解的 inline 是在编译阶段把函数中的代码拷贝到函数调用出,所以两个代码应该是等价的,为什么性能上有差别?
另外我还尝试去掉 inline 结果速度比用 inline 还快。是我对 inline 的理解不对吗?