1 概念
影响性能的一个重要因素是内联技巧,内联函数也可称为内嵌函数。在C++中,函数调用需要建立栈环境,进行参数复制,保护调用现场,返回时,还要进行返回值复制,恢复调用现场。这些工作都是与完成特定任务的操作无关的额外开销。程序效“率由于该项工作而受到影响,所以,流行的CPU都已经将函数调用的额外工作硬件化了,以此来减少运行开销。尽管如此,调用工作还是有一些微小的开销的。
//非内嵌式函数
#include<iostream>
using namespace std;
bool isnum(char ch);
int main()
{
char str;
while (cin >> str && str != '\n')
{
if(isnum(str))
cout << "num"<<endl;
else
cout << "nonum"<<endl;
}
return 0;
}
bool isnum(char ch)
{
return ch >= '0' && ch <='9' ? 1 : 0;
}
//内联函数
#include<iostream>
using namespace std;
inline bool isnum(char ch); // 必须在调用前就声明内联
int main()
{
char str;
while (cin >> str && str != '\n')
{
if(isnum(str))
cout << "num"<<endl;
else
cout << "nonum"<<endl;
}
return 0;
}
bool isnum(char ch)
{
return ch >= '0' && ch <= '9' ? 1 : 0;
}
2 使用建议
内联函数使用的场合一般为:
(1)函数体适当小,这样就使嵌入工作容易进行,不会破坏原调用主体。
(2)程序中特别是在循环中反复执行该函数,这样就使嵌入的效率相对较高。
(3)程序并不多处出现该函数调用,这样就使嵌入工作量相对较少,代码量也不会剧增
(4)如switch和while/递归函数等,编译将无视内联声明,只是视同普通函数那样产生调用代码。
3 效率测试
如下矩阵计算,用VS两者运行时间一样,估计现在的编译器聪明得很。
另外编程不需要这种不确定性,这种设计跟编程的思想就是冲突的。
#include<iostream>
#include<ctime>
using namespace std;
int calc1(int a, int b)
{
return a + b;
}
inline int calc2(int a, int b)
{
return a + b;
}
int main()
{
int x[1000]={};
int y[1000] = {};
int z[1000] = {};
clock_t t = clock();
for (int i = 0; i < 1000; i++)
for (int j = 0; j < 1000; j++)
for (int z = 0; z < 1000; z++)
{
z[i] = calc1(x[j] , y[z]);
}
cout << "no use inline" << (clock() - t) / CLK_TCK << endl;
clock_t t1 = clock();
for (int i = 0; i < 1000; i++)
for (int j = 0; j < 1000; j++)
for (int z = 0; z < 1000; z++)
{
z[i] = calc1(x[j] , y[z]);
}
cout << " use inline" << (clock() - t1) / CLK_TCK << endl;
return 0;
}