Why C++ output is too much slower than C? -
i fan of c++, today figured out slow file output of program. so, designed experiment compare speed of c++ file output c. suppose have piece of code :
int num = 20000000; vector <int> v; ( int = 0; < num; i++ ) { v.push_back(i); }
now run 2 separate code, 1 in c++ :
int = time(0); cout << "start" << endl; ofstream fout("c++.txt"); for(size_t = 0; < v.size(); ++i) { fout<< v[i] << endl; } fout.close(); cout << time(0) - << endl;
and 1 in c :
int = time(0); printf("start\n"); file *fp = fopen("c.txt", "w"); for(size_t = 0; < v.size(); ++i) { fprintf(fp, "%d\n", v[i]); } fclose(fp); printf("%ld\n", time(0) - now);
c++ program works surprisingly slower! on system, c program runs in 3 seconds while c++ program takes 50 seconds run! there reasonable explanation this?
it's because of how flushing stream disk in c++ code. inserting endl
stream inserts new line , flushes buffer, while fprintf
doesn't cause buffer flush.
so c++ example performs 20,000,000 buffer flushes while c example flush disk when file handles buffer full.
Comments
Post a Comment