I have a question regarding C++/CLI vs Native C++ speeds. I have written a little test application and I am seeing very surprising results.
It seems that the unmanaged C++/CLI code is significantly slower. Basically I created two console apps. One a standard win32 console app and a CLR console app
Here is the code I did for a test. I kept the code exactly the same in all versions of the test.
const int NumberOfTests = 10000000;
void GrowBalance(int numberOfYears)
{
std::cout<<"Called"<<std::endl;
DWORD startTime = GetTickCount();
int numberOfRandom = 0;
for(int i = 0; i < NumberOfTests; i++)
{
double dBalance = 10000.0;
for(int year = 0; year < numberOfYears; year++)
{
dBalance *= 1.05;
if(dBalance > 20000.00 && dBalance < 22000.00)
{
numberOfRandom++;
}//if
}//for
}//for
DWORD endTime = GetTickCount();
std::cout<<"Time Elapsed: "<<endTime - startTime<<std::endl;
std::cout<<"Number of random: "<<numberOfRandom<<std::endl;
}
Output managed code:
Called
Time Elapsed: 9937
Number of random: 20000000
Output managed code with pragma managed(push, off):
Called
Time Elapsed: 24516
Number of random: 20000000
Output native code:
Called
Time Elapsed: 2156
Number of random: 20000000
In the mains just calling GrowBalance with 90 years specified. Pretty basic test. Is there something I am doing wrong or am I really looking at code that is going to be 4.5 times slower by using C++/CLI. And I also don’t understand the case of turning managed code off. Everything I have read said this would compile the code to native C++ but it is insanely slower. Any help with this would be very much appreciated.
Update:
I just ran this test in visual studio 2005 instead of 2008. Native C++ performance is matched.
Update #2:
I just put my test code into a class instead of a single function and am getting much better results. Now the mixed code is preforming at an average run time of ~5000ms
But in 2005 I am seeing much much faster results. Average run time of about ~1875ms. Maybe I will just stick to 2005 for my CLI development. Unless someone has a reason why this could be occurring.
One thing you may be running into is that for native C++, optimizations are controlled by command-line arguments to the compiler, but for managed code, optimizations are controlled by how you start the application (i.e. if you launch in debugger, many optimizations are disabled even if you did an optimized build). You shouldn’t be running performance tests “in” Visual Studio at all.
The native compiler also has a LOT of extra optimizations. It might even be smart enough to figure out that
dBalanceis strictly increasing, and continuing the inner for loop oncedBalance > 22000.0has no observable side effects.What happens in all three cases if you change that inner for loop like this (it will only do 17 iterations, as long as
numberOfYears >= 17)?How about:
And how about: