我正在测试 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;
}
我只测试函数调用速度,在启动时就可以获取地址。所以失去的性能并不重要。