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++ )

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;
cout << time(0) - now << endl;

and one in C :

int now = time(0);
FILE *fp = fopen("c.txt", "w");
for(size_t i = 0; i < v.size(); ++i)
    fprintf(fp, "%d\n", v[i]);
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?


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.