Search code examples
c#c++execution

C++ and C# Speed Test - Strange Result


For my new project which needs high speed calculation, I am trying to chose between C++ and C#. I've always heard that C# is reasonable in speed. I knew that it is slower that C and C++, but my exception was that the difference is not huge! So I wrote two codes in C++ and C# to test them myself.

The result was around 5:09 to 5:55 second for C++ versus 11408 to 11960 second for C#.

So is something wrong with my codes, or this is what it really is? Here is my C++ code:

clock_t tStart = clock();
std::ofstream myfile;
myfile.open("log.txt");
std::string pi;

int limit = 50;
for (int i = 0; i < limit; i++)
{
    for (int j = 0; j < limit; j++)
    {
        for (int k = 0; k < limit; k++)
        {
            double val = sin(i *i + j *j + k *k);
            pi = std::to_string(val);
            myfile << pi<<"\n";
        }
    }
}
myfile.close();
printf("Time taken: %.2fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC);
getchar();
return 0;

and here is my C# code:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string path = @"c:\log.txt";
int limit = 50;
for (int i = 0; i < limit; i++)
{
     for (int j = 0; j < limit; j++)
     {
          for (int k = 0; k < limit; k++)
          {
                double val = Math.Sin(i *i + j *j + k *k);
                using (StreamWriter sw = File.AppendText(path))
                {
                    sw.WriteLine(val.ToString("F6"));
                }
          }
     }
}
stopwatch.Stop();
Console.Write(stopwatch.ElapsedMilliseconds);
Console.ReadKey(true);

My OS is Win7 64bit. Thanks in advance for your time.

@EDIT: why changing double val = Math.Sin(i *i + j *j + k *k); to double val = Math.Sin(i^2 + j^2 + k^2); in C#, produces totally different answers?


Solution

  • for (int j = 0; j < limit; j++)
    {
        for (int k = 0; k < limit; k++)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                //...
            }          
        }
    }
    

    Your results are not surprising - you are opening file and creating and disposing StreamWriter at the every iteration. You should create it once:

    using (StreamWriter sw = File.AppendText(path))
    {
        for (int j = 0; j < limit; j++)
        {
            for (int k = 0; k < limit; k++)
            {
                    //...   
            }
        }
    }