Note that there are some explanatory texts on larger screens.

plurals
  1. POC# vs C - Big performance difference
    text
    copied!<p>I'm finding massive performance differences between similar code in C anc C#.</p> <p>The C code is:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;math.h&gt; main() { int i; double root; clock_t start = clock(); for (i = 0 ; i &lt;= 100000000; i++){ root = sqrt(i); } printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC); } </code></pre> <p>And the C# (console app) is:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { DateTime startTime = DateTime.Now; double root; for (int i = 0; i &lt;= 100000000; i++) { root = Math.Sqrt(i); } TimeSpan runTime = DateTime.Now - startTime; Console.WriteLine("Time elapsed: " + Convert.ToString(runTime.TotalMilliseconds/1000)); } } } </code></pre> <p>With the above code, the C# completes in 0.328125 seconds (release version) and the C takes 11.14 seconds to run.</p> <p>The c is being compiled to a windows executable using mingw.</p> <p>I've always been under the assumption that C/C++ were faster or at least comparable to C#.net. What exactly is causing the C to run over 30 times slower?</p> <p>EDIT: It does appear that the C# optimizer was removing the root as it wasn't being used. I changed the root assignment to root += and printed out the total at the end. I've also compiled the C using cl.exe with the /O2 flag set for max speed.</p> <p>The results are now: 3.75 seconds for the C 2.61 seconds for the C#</p> <p>The C is still taking longer, but this is acceptable</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload