Peter Olcott said:
http://www.tommti-systems.de/go.htm...ain-Dateien/reviews/languages/benchmarks.html
The above link shows that C# is 450% slower on something as simple as a
nested loop. Is this because .NET is inherently slower or does the C#
compiler merely produce code that is not as well optimized as the C++
compiler?
Argggg... broken benchmarks published by people who have no clue what they
are talking about, sorry.
Just to mention what's broken in the function that's 450% slower here is the
correct code for C#.
//x was an int type, but should be a long, else the result x will overflow
several hundred times (and be incorrect), and negatively impacting the
execution time.
int a = 0, b = 0, c = 0, d= 0, e = 0, f = 0;
long x=0; // see note above
startTime = DateTime.Now;
for (a=0; a!=n; a++)
for (b=0; b!=n; b++)
for (c=0; c!=n; c++)
for (d=0; d!=n; d++)
for (e=0; e!=n; e++)
for (f=0; f!=n; f++)
x+=a+b+c+d+e+f;
[1] This is the correct code which is still ~50% slower than the (corrected)
native C++ code ( __int64 x=0
.
Herewith are the timings measured on my system.
1) C# with /o+
Nested Loop elapsed time: 10015 ms - 479232000000
2) VC++ with /O2 /EHsc (native code)
Nested Loop elapsed time: 6171 ms 479232000000
Note that this is a sample where the native C++ compiler optimizer does a
better job than C# and the JIT compiler/optimizer.
3) VC++ with /O2 /clr (managed code, unverifiable!!!)
Nested Loop elapsed time: 6406 ms 479232000000
In this particular case, the C++/CLI compiler optimizer does a better job
than C# when generating the IL, at the cost of generating unverifiable
code!!.
3) And here to please you all is the result of the same function compiled to
safe IL
// function slightly adapted to make it possible to compile with /clr:safe
(verifiable) code
static void nl(int n) {
int a, b, c, d, e, f;
__int64 x = 0;
Stopwatch^ stopWatch = gcnew Stopwatch;
stopWatch->Start();
for (a=0; a<n; a++)
for (b=0; b<n; b++)
for (c=0; c<n; c++)
for (d=0; d<n; d++)
for (e=0; e<n; e++)
for (f=0; f<n; f++)
x+=a+b+c+d+e+f;
stopWatch->Stop();
TimeSpan ts = stopWatch->Elapsed;
System::Console::WriteLine("Nested Loop elapsed time: {0} sec.{1} msec.
{2}\n", ts.Seconds, ts.Milliseconds, x);
}
Nested Loop elapsed time: 12 sec.812 msec. 479232000000
Notice the result is slightly slower (dispite the O2 optimizing flag) than
the C# code, this is because the IL is constrained by the verifier (for both
C# and C++/CLI in safe mode). So here C# emits slightly better IL.
Willy.