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?