title: C# vs C - Big performance difference
body: <p>I'm finding massive performance differences between similar code in C and 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(&quot;Time elapsed: %f\n&quot;, ((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(&quot;Time elapsed: &quot; + 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 code 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 <code>root +=</code> 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>