Why C++ output is too much slower than C?

I am actually a fan of C++, but today I figured out very slow file output of my program. So, I designed an experiment to compare speed of C++ file output with C. Suppose we have this piece of code :

int Num = 20000000;
vector <int> v;
for ( int i = 0; i < Num; i++ )
{
    v.push_back(i);
}

Now I run two separate code, one in C++ :

int now = time(0);
cout << "start" << endl;
ofstream fout("c++.txt");
for(size_t i = 0; i < v.size(); ++i)
{
    fout<< v[i] << endl;
}
fout.close();
cout << time(0) - now << endl;

and one in C :

int now = time(0);
printf("start\n");
FILE *fp = fopen("c.txt", "w");
for(size_t i = 0; i < v.size(); ++i)
{
    fprintf(fp, "%d\n", v[i]);
}
fclose(fp);
printf("%ld\n", time(0) - now);

C++ program works surprisingly slower! On my system, C program runs in 3 seconds while C++ program takes about 50 seconds to run! Is there any reasonable explanation for this?

Answers


It's likely because of how often you are flushing the stream to disk in the C++ code. Inserting endl into a stream inserts a new line and flushes the buffer, while fprintf doesn't cause a buffer flush.

So your C++ example performs 20,000,000 buffer flushes while your C example will only flush to disk when the file handles buffer is full.


Need Your Help

get next cell (to the right) in a table using jquery

javascript jquery html

EDIT Sorry for the mix up I was looking for the cell to the right >.&lt;

Multiple items selection in an Android ListView with custom view

android android-listview multipleselection android-actionmode

I am trying to implement in an Android application a multiple items selection in an Android ListView to allow the user to delete severals rows in one action with the help of the action mode.