Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 888
Ehsan Haghshenas Avatar asked May 03 '13 03:05

Ehsan Haghshenas


1 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.

like image 130
shf301 Avatar answered Sep 17 '22 12:09

shf301