我遇到了C ++函数性能问题,使用下面的代码进行测试。 queryInterface
和queryInterface1
的实现几乎相同。唯一的区别是queryInterface
调用classType
函数,classType
函数调用classType1
,queryInterface1
直接调用classType1
。 queryInterface1
的效果不佳,需要的时间是queryInterface
的两倍。 queryInterface1
的问题是什么?为什么?用MSVC编译。请参阅控制台中的输出:
queryInterface()的时间成本:2453
queryInterface1()的时间成本:4961
#include <string>
#include <time.h>
#include <iostream>
#include <unordered_map>
using namespace std;
namespace
{
int find(const string& name)
{
return 0;
}
class A
{
public:
static int classType();
static int classType1();
virtual void* queryInterface(int id) const
{
if (A::classType() == id)
return const_cast<A*>(this);
return nullptr;
}
virtual void* queryInterface1(int id) const
{
if (A::classType1() == id)
return const_cast<A*>(this);
return nullptr;
}
};
int A::classType()
{
static int s_classType = classType1();
return s_classType;
}
int A::classType1()
{
static int s_classType = find("A");
return s_classType;
}
}
int main()
{
clock_t start, stop;
const size_t count = 1000000000;
A* pA = new A;
start = clock();
for (size_t i = 0; i < count; i++)
{
pA->queryInterface(A::classType());
}
stop = clock();
cout << "time cost of queryInterface(): " << stop - start << endl;
start = clock();
for (size_t i = 0; i < count; i++)
{
pA->queryInterface1(A::classType1());
}
stop = clock();
cout << "time cost of queryInterface1(): " << stop - start << endl;
return 0;
}
答案 0 :(得分:4)
性能差异是由于编译器在A::classType1
的调用中设置了安全检查。这些都是在每次调用时设置的,即使只有一次调用find
函数才真正需要它。
安全检查确定堆栈是否已被覆盖,可能破坏堆栈帧,包括返回地址。
如果s_classType
为常量整数而不是调用find
,则更改初始值会导致queryInterface1
调用执行速度加快。
可以使用/GS-
编译器选项禁用安全检查。