Reputation: 929
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?
Upvotes: 0
Views: 245
Reputation: 408
The big difference in your test is that for the C++ one, you open and Close the file outside the loop, which means it only happen 1 time.
In your C# test, you will open the file, do file seek to the end and then Close it for every iteration. This will be a huge time sink.
You should instead move the Creation of the streamwriter to be above your loop, and then Close it after you exit the loop.
I'm refering to the code
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(val.ToString("F6"));
}
Upvotes: 2
Reputation: 437
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++)
{
//...
}
}
}
Upvotes: 3