Is it recommended that C++ programmers frequently write lines like
std::cout << "output: " << i << " and " << j << std::flush;
//more
std::cout << "ending newline." << std::endl; //endl does flush
In other words, in output lines that don't have endl
, should we be flush
ing alot, just in case? Or is this not really needed anymore these days on most platforms?
Flushing is generally not the greatest habit to get into, as flushing can slow down your program at times if you're constantly writing out to IO. You can control how you flush by either explicitly using
std::endl
orstd::flush
(withstd::endl
just inserting a\n
into a stream and then callingflush
).@StackedCrooked in the C++ Lounge put together an experiment about the cost of flushing versus not flushing at all: http://coliru.stacked-crooked.com/view?id=55c830cf9a144559f31963de41fa9405-f674c1a6d04c632b71a62362c0ccfc51
Not-flushing does relatively well after repeated use, while flushing adds a bit of overhead everytime you invoke it: you are honestly better off not manually
std::flush
-ing your streams. Just do it once at the end of the program or after the end of a critical section of code.It's also good to note that you should probably flush just before you do anything with the user, so the program isn't not-writing things to the output that a user should be seeing in a Log File or other place.
EDIT: Relevant analogy: In simple terms, what is the purpose of flush() in ostream
Your average program does not require frequent flushing. Flushing is something nearer to a special case needed in a few situations:
If buffering is not needed, it would be better to disable buffering in the first place instead of throwing in a lot of flushes.
Most of the time, programs benefit by having buffering enabled. Sometimes they generate a few characters here and there. Other times they output a blast of lines.
In all my decades of engineering, my most dramatic performance increases are often realized simply by improving buffering. Sometimes by increasing the default
FILE
buffer size above 512 bytes (the default) to 4K or 32K (sometimes higher). Other times by adding a layer of buffering or caching. Usually there is high overhead with each trip through the operating system's i/o system. Reducing the total number of system calls is (usually) an easy and highly effective scheme to improve performance.