简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM