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, simply stick with cout but don’t use endl since it flushes the buffer implicitly (slowing the process down). Use "\n" instead. It can be interesting if you produce large outputs.
The direct answer is that yes, that’s okay.
A lot of people have thrown around various ideas of how to improve speed, but there seems to be quite a bit of disagreement over which is most effective. I decided to write a quick test program to get at least some idea of which techniques did what.
I ran this on Windows after compiling with VC++ 2013 (both x86 and x64 versions). Output from one run (with output redirected to a disk file) looked like this:
As expected, results vary, but there are a few points I found interesting:
I’ve recently edited the code to force a call to
printf. Anders Kaseorg was kind enough to point out–thatg++recognizes the specific sequenceprintf("%s\n", foo);is equivalent toputs(foo);, and generates code accordingly (i.e., generates code to callputsinstead ofprintf). Moving the format string to a global array, and passing that as the format string produces identical output, but forces it to be produced viaprintfinstead ofputs. Of course, it’s possible they might optimize around this some day as well, but at least for now (g++ 5.1) a test withg++ -O3 -Sconfirms that it’s actually callingprintf(where the previous code compiled to a call toputs).