【发布时间】:2013-05-17 14:53:05
【问题描述】:
我在我的电脑(Intel i3-3220 @ 3.3GHz,Fedora 18)上运行了一个基准测试,得到了非常意想不到的结果。函数指针实际上比内联函数快一点。
代码:
#include <iostream>
#include <chrono>
inline short toBigEndian(short i)
{
return (i<<8)|(i>>8);
}
short (*toBigEndianPtr)(short i)=toBigEndian;
int main()
{
std::chrono::duration<double> t;
int total=0;
for(int i=0;i<10000000;i++)
{
auto begin=std::chrono::high_resolution_clock::now();
short a=toBigEndian((short)i);//toBigEndianPtr((short)i);
total+=a;
auto end=std::chrono::high_resolution_clock::now();
t+=std::chrono::duration_cast<std::chrono::duration<double>>(end-begin);
}
std::cout<<t.count()<<", "<<total<<std::endl;
return 0;
}
编译
g++ test.cpp -std=c++0x -O0
“toBigEndian”循环总是在 0.26-0.27 秒左右完成,而“toBigEndianPtr”则需要 0.21-0.22 秒。
更奇怪的是,当我删除 'total' 时,函数指针在 0.35-0.37 秒处变慢,而内联函数大约为 0.27-0.28 秒。
我的问题是:
为什么存在'total'时函数指针比内联函数快?
【问题讨论】:
-
你没有优化。分析未优化的代码是没有意义的。
-
加上-O3速度还是一样的。
-
函数指针总是在 0.22 秒,内联函数在 0.26。
-
我看到的恰恰相反。
-
奇怪的是,当我分析内联函数时,总是会发生打嗝。我已经运行了大约 50 次基准测试,交替使用内联和指针,内联几乎总是较慢。
标签: c++ performance function-pointers inline-functions