我在下面发布了一些代码,以测试使用Visual Studio 2010从本机c++和c#从c++/cli调用方法的性能(以毫秒为单位) 。我有一个单独的本地 c++ 项目,它被编译成 dll。当我从 c++ 调用 c++ 时,我得到的预期结果比托管的同类产品快得多(大约 4 倍)。但是,当我从 c++/cli 调用 c++ 时,性能会慢 10 倍。
这是从 c++/cli 调用本机 c++ 时的预期行为吗?我的印象是不应该有显着差异,但这个简单的测试显示不同。这可能是 c++ 和 c++/cli 编译器之间的优化差异吗?
更新
我对 cpp 进行了一些更新,因此我不会在紧密循环中调用方法(正如 Reed Copsey 指出的那样),结果证明性能差异微不足道或非常小。当然,这取决于互操作的完成方式。
。H
#ifndef CPPOBJECT_H
#define CPPOBJECT_H
#ifdef CPLUSPLUSOBJECT_EXPORTING
#define CLASS_DECLSPEC __declspec(dllexport)
#else
#define CLASS_DECLSPEC __declspec(dllimport)
#endif
class CLASS_DECLSPEC CPlusPlusObject
{
public:
CPlusPlusObject(){}
~CPlusPlusObject(){}
void sayHello();
double getSqrt(double n);
// Update
double wasteSomeTimeWithSqrt(double n);
};
#endif
.cpp
#include "CPlusPlusObject.h"
#include <iostream>
void CPlusPlusObject::sayHello(){std::cout << "Hello";}
double CPlusPlusObject::getSqrt(double n) {return std::sqrt(n);}
double CPlusPlusObject::wasteSomeTimeWithSqrt(double n)
{
double result = 0;
for (int x = 0; x < 10000000; x++)
{
result += std::sqrt(n);
}
return result;
}
c++/cli
const unsigned set = 100;
const unsigned repetitions = 1000000;
double cppcliTocpp()
{
double n = 0;
System::Diagnostics::Stopwatch^ stopWatch = gcnew System::Diagnostics::Stopwatch();
stopWatch->Start();
while (stopWatch->ElapsedMilliseconds < 1200){n+=0.001;}
stopWatch->Reset();
for (int x = 0; x < set; x++)
{
stopWatch->Start();
CPlusPlusObject cplusplusObject;
n += cplusplusObject.wasteSomeTimeWithSqrt(123.456);
/*for (int i = 0; i < repetitions; i++)
{
n += cplusplusObject.getSqrt(123.456);
}*/
stopWatch->Stop();
System::Console::WriteLine("c++/cli call to native c++ took " + stopWatch->ElapsedMilliseconds + "ms.");
stopWatch->Reset();
}
return n;
}
double cppcliTocSharp()
{
double n = 0;
System::Diagnostics::Stopwatch^ stopWatch = gcnew System::Diagnostics::Stopwatch();
stopWatch->Start();
while (stopWatch->ElapsedMilliseconds < 1200){n+=0.001;}
stopWatch->Reset();
for (int x = 0; x < set; x++)
{
stopWatch->Start();
CSharp::CSharpObject^ cSharpObject = gcnew CSharp::CSharpObject();
for (int i = 0; i < repetitions; i++)
{
n += cSharpObject->GetSqrt(123.456);
}
stopWatch->Stop();
System::Console::WriteLine("c++/cli call to c# took " + stopWatch->ElapsedMilliseconds + "ms.");
stopWatch->Reset();
}
return n;
}
double cppcli()
{
double n = 0;
System::Diagnostics::Stopwatch^ stopWatch = gcnew System::Diagnostics::Stopwatch();
stopWatch->Start();
while (stopWatch->ElapsedMilliseconds < 1200){n+=0.001;}
stopWatch->Reset();
for (int x = 0; x < set; x++)
{
stopWatch->Start();
CPlusPlusCliObject cPlusPlusCliObject;
for (int i = 0; i < repetitions; i++)
{
n += cPlusPlusCliObject.getSqrt(123.456);
}
stopWatch->Stop();
System::Console::WriteLine("c++/cli took " + stopWatch->ElapsedMilliseconds + "ms.");
stopWatch->Reset();
}
return n;
}
int main()
{
double n = 0;
n += cppcliTocpp();
n += cppcliTocSharp();
n += cppcli();
System::Console::WriteLine(n);
System::Console::ReadKey();
}