【问题标题】:Dll function call is faster then a normal function call?dll函数调用比普通函数调用快吗?
【发布时间】:2013-01-11 08:43:11
【问题描述】:

我正在测试 DLL 中导出函数和普通函数的速度。 DLL 中的导出函数怎么可能快得多?

100000000 function calls in a DLL cost: 0.572682 seconds
100000000 normal function class cost: 2.75258 seconds

这是DLL中的函数:

extern "C" __declspec (dllexport) int example()
{
    return 1;
}

这是正常的函数调用:

int example()
{
    return 1;
}

我是这样测试的:

int main()
{
    LARGE_INTEGER frequention;
    LARGE_INTEGER dllCallStart,dllCallStop;
    LARGE_INTEGER normalStart,normalStop;
    int resultCalculation;

    //Initialize the Timer
    ::QueryPerformanceFrequency(&frequention);
    double frequency = frequention.QuadPart;
    double secondsElapsedDll = 0;
    double secondsElapsedNormal = 0;

    //Load the Dll
    HINSTANCE hDll = LoadLibraryA("example.dll");

    if(!hDll)
    {
        cout << "Dll error!" << endl;
        return 0;
    }

    dllFunction = (testFunction)GetProcAddress(hDll, "example");

    if( !dllFunction )
    {
        cout << "Dll function error!" << endl;
        return 0;
    }

    //Dll
    resultCalculation = 0;
    ::QueryPerformanceCounter(&dllCallStart);
    for(int i = 0; i < 100000000; i++)
        resultCalculation += dllFunction();
    ::QueryPerformanceCounter(&dllCallStop);

    Sleep(100);

    //Normal
    resultCalculation = 0;
    ::QueryPerformanceCounter(&normalStart);
    for(int i = 0; i < 100000000; i++)
        resultCalculation += example();
    ::QueryPerformanceCounter(&normalStop);

    //Calculate the result time
    secondsElapsedDll = ((dllCallStop.QuadPart - dllCallStart.QuadPart) / frequency);
    secondsElapsedNormal = ((normalStop.QuadPart - normalStart.QuadPart) / frequency);

    //Output
    cout << "Dll: " << secondsElapsedDll << endl; //0.572682
    cout << "Normal: " << secondsElapsedNormal << endl; //2.75258

    return 0;
}

我只测试函数调用速度,在启动时就可以获取地址。因此,性能损失并不重要。

【问题讨论】:

  • 去掉extern "C"会有什么结果?
  • 我不相信,因为 this 普通函数会被内联,但来自 DLL 的函数不能被内联。所以我认为你一定是在做一些不恰当的事情。您使用的是发布版本吗?
  • 你是如何编译这两个项目的?某些优化选项可能决定根本不调用该函数,这样更快。
  • 只是为了好玩,将 int resultCalculation; 更改为 volatile int resultCalculation; 并重新运行您的测试。另外,交换顺序(先运行本地,然后运行 ​​DLL)。
  • volatile int 是诀窍。现在正常通话更快了。谢谢。所以优化是问题所在。

标签: c++ windows performance dll


【解决方案1】:

对于一个非常小的函数,区别在于函数返回/清理参数的方式。

但是,这不应该有太大的不同。我认为编译器意识到您的函数对 resultCalcuation 没有任何作用并对其进行优化。尝试使用两个不同的变量,然后打印它们的值。

【讨论】:

  • 优化确实是问题所在。当我交换 int resultCalculation;对 volatile int 结果计算;那么正常通话会更快。 (感谢@WhozCraig。)
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多