Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my C# code is faster than my C code?

Tags:

c++

c

c#

I am launching these two console applications on Windows OS. Here is my C# code

int lineCount = 0;
StreamWriter writer = new StreamWriter("txt1.txt",true);
for (int i = 0; i < 900; i++)
{
    for (int k = 0; k < 900; k++)
    {
        writer.WriteLine("This is a new line" + lineCount);
        lineCount++;
    }
}

writer.Close();
Console.WriteLine("Done!");
Console.ReadLine();

And here is my C code. I am assuming it is C because I included cstdio and used standard fopen and fprintf functions.

FILE *file = fopen("text1.txt","a");

for (size_t i = 0; i < 900; i++)
{
    for (size_t k = 0; k < 900; k++)
    {
        fprintf(file, "This is a line\n");
    }
}

fclose(file);
cout << "Done!";

When I start C# program I immediately see the message "Done!". When I start C++ program (which uses standard C functions) it waits at least 2 seconds to complete and show me the message "Done!".

I was just playing around to test their speeds, but now I think I don't know lots of things. Can somebody explain it to me?

NOTE: Not a possible duplicate of "Why is C# running faster than C++? ", because I am not giving any console output such as "cout" or "Console.Writeline()". I am only comparing filestream mechanism which doesn't include any interference of any kind that can interrupt the main task of the program.

like image 929
ozgur Avatar asked Aug 10 '15 14:08

ozgur


1 Answers

You are comparing apples and potatoes. Your C/C++ program is not doing any buffering at all. If you were to use a fstream with buffering your results would be a lot better : See also this std::fstream buffering vs manual buffering (why 10x gain with manual buffering)?

like image 93
Philip Stuyck Avatar answered Sep 29 '22 02:09

Philip Stuyck