Inspired by the question of whether to use streams or file functions, and that streams are usually slower.
I sketched a test program (code below), tested it on Open Watcom and Visual C ++ 2015. The results of the output to the console window and to the file are compared with functions for working with streams and files. To work with the old Watcom, I used clock() for the measurement, and it turned out that the OW function ios::sync_with_stdio() recommended in the above question was obsolete , so it was removed for this compiler.
Checked under Windows 7 x64. There are actually two questions - and what is being done with other compilers and operating systems, and how, in fact, you can speed up the output - both console in general and streaming to the level of functions C. Are there any optimization options? What caused the observed variation?
Here is the code:
#include <vector> #include <iostream> #include <fstream> #include <iomanip> #include <cstdio> #include <ctime> using namespace std; clock_t bench(void(*func)()) { clock_t start = clock(); func(); clock_t stop = clock(); return stop - start; } const int Count = 100000; vector<double> dv; vector<int> iv; FILE * outfile = 0; ofstream * outstream = 0; void printf_console() { for(int i = 0; i < Count; ++i) printf("%d %lf ",iv[i],dv[i]); } void printf_file() { for(int i = 0; i < Count; ++i) fprintf(outfile, "%d %lf ",iv[i],dv[i]); } void stream_console() { for(int i = 0; i < Count; ++i) cout << iv[i] << " " << dv[i] << " "; } void stream_file() { for(int i = 0; i < Count; ++i) *outstream << iv[i] << " " << dv[i] << " "; } int main(int argc, const char * argv[]) { for(int i = 0; i < Count; ++i) { dv.push_back(rand()/double(RAND_MAX)); iv.push_back(rand()); } outfile = fopen("test.dat","wt"); outstream = new ofstream("test.stream"); clock_t out_printf_console = bench(printf_console); clock_t out_printf_file = bench(printf_file); clock_t out_cout_sync = bench(stream_console); clock_t out_stream_file = bench(stream_file); ios::sync_with_stdio(false); clock_t out_cout_async = bench(stream_console); ios::sync_with_stdio(true); clock_t out_cout_rsync = bench(stream_console); cerr << "\n\n"; cerr << "printf console: " << setw(10) << out_printf_console << endl; cerr << "printf file : " << setw(10) << out_printf_file << endl; cerr << "stream sync console: " << setw(10) << out_cout_sync << endl; cerr << "stream async console: " << setw(10) << out_cout_async << endl; cerr << "stream rsync console: " << setw(10) << out_cout_rsync << endl; cerr << "stream file : " << setw(10) << out_stream_file << endl; delete outstream; fclose(outfile); } Here are the results:
Open Watcom: VC++ 2015: printf console: 16739 21806 printf file : 62 69 stream sync console: 16723 87678 stream async console: 16754 86899 stream rsync console: 16692 87254 stream file : 141 150 PS It is surprising that, in the general case, VC ++ beats Open Watcom, and here it loses capital for it, especially when streaming to the console.