我遇到了一个 C++ 函数性能问题,使用下面的代码进行测试。 queryInterface
和queryInterface1
的实现几乎相同。唯一的区别是queryInterface
调用classType
函数,而classType
函数调用classType1
,queryInterface1
直接调用 classType1
。 queryInterface1
的性能很差,它花费的时间是queryInterface
的两倍。 queryInterface1
的问题是什么,为什么?用 MSVC 编译。查看控制台输出:
time cost of queryInterface(): 2453
time cost of 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;
}
最佳答案
性能差异是由于编译器在调用 A::classType1
时设置了安全检查。这些都是在每次调用时设置的,即使只有在调用 find
函数时才真正需要它。
安全检查确定堆栈是否已被覆盖,从而可能破坏堆栈帧,包括返回地址。
将 s_classType
的初始值更改为常量整数,而不是调用 find
,可以更快地执行 queryInterface1
调用。
可以使用 /GS-
编译器选项禁用安全检查。
关于C++函数性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548047/