After performing some tests I noticed that printf
is much faster than cout
. I know that it's implementation dependent, but on my Linux box printf
is 8x faster. So my idea is to mix the two printing methods: I want to use cout
for simple prints, and I plan to use printf
for producing huge outputs (typically in a loop). I think it's safe to do as long as I don't forget to flush before switching to the other method:
cout << "Hello" << endl;
cout.flush();
for (int i=0; i<1000000; ++i) {
printf("World!\n");
}
fflush(stdout);
cout << "last line" << endl;
cout << flush;
Is it OK like that?
Update: Thanks for all the precious feedbacks. Summary of the answers: if you want to avoid tricky solutions, just simply don't use endl
with cout
since it flushes the buffer implicitly. Use "\n"
instead. It can be interesting if you produce large outputs.