C++ Dll函数调用比普通函数调用快?
我在测试DLL中导出函数和普通函数的速度。DLL中导出的函数怎么可能快得多C++ Dll函数调用比普通函数调用快?,c++,windows,performance,dll,C++,Windows,Performance,Dll,我在测试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
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;
}
intmain()
{
大整数频率;
大整数dllCallStart,dllCallStop;
大整数normalStart,normalStop;
结果计算;
//初始化计时器
::QueryPerformanceFrequency(&frequenction);
双频=频率。四分之一;
双秒selapsedll=0;
双秒SelapsedNormal=0;
//加载Dll
HINSTANCE hDll=LoadLibraryA(“example.dll”);
如果(!hDll)
{
cout对于非常小的函数,区别在于函数返回/清除参数的方式
但是,这不会有太大的区别。我认为编译器意识到您的函数对ResultCalculation没有任何作用,并对其进行了优化。尝试使用两个不同的变量,然后打印它们的值。如果去掉extern“C”,结果会是什么
?我不相信,因为这个普通函数将被内联,但DLL中的函数无法内联。所以我认为您一定做了一些不恰当的事情。您使用的是发布版本吗?您是如何编译这两个项目的?某些优化选项可能决定根本不调用该函数,这会更快。只是为了好玩,将int-resultCalculation;
更改为volatile int-resultCalculation;
,然后重新运行测试。另外,交换顺序(先运行本地,然后运行DLL).volatile int是诀窍。现在正常调用更快。谢谢。所以优化是问题。优化确实是问题。当我将int resultCalculation;交换到volatile int resultCalculation;时,正常调用更快。(谢谢@WhozCraig。)