C++函数性能问题

标签 c++ string performance function visual-c++

我遇到了一个 C++ 函数性能问题,使用下面的代码进行测试。 queryInterfacequeryInterface1 的实现几乎相同。唯一的区别是queryInterface调用classType函数,而classType函数调用classType1queryInterface1 直接调用 classType1queryInterface1 的性能很差,它花费的时间是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/

相关文章:

c++ - 如何从文件中读取字节? C++

php - 自定义排序字符串——如果以特定字符串开头,则按字母顺序排列

python - 高效交换numpy数组中的元素

android - 当 Android 小部件 RemoteViewService 被销毁时

c++ - 使用 gprof 和 boost

c++ - 如何将 C++ 对象返回到 lua 5.2?

c++ - 如何在 C/C++ 中收到文件/目录更改的通知,最好使用 POSIX

linux - 预期为整数表达式 (Bash)

ruby - 在 Ruby 中扫描字符串数组以查找匹配项

python - 使用 Numpy 快速索引