Should C++ programmers use std::flush frequently?

2020-07-02 01:04发布

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 flushing alot, just in case? Or is this not really needed anymore these days on most platforms?

标签: c++
2条回答
孤傲高冷的网名
2楼-- · 2020-07-02 01:38

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 or std::flush (with std::endl just inserting a \n into a stream and then calling flush).

@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

查看更多
够拽才男人
3楼-- · 2020-07-02 01:45

Your average program does not require frequent flushing. Flushing is something nearer to a special case needed in a few situations:

  • Interacting with a human or other system: flushing output before waiting for input is sensible.
  • Going dormant for awhile: Flushing before extended sleep or waiting simplifies examination of logfiles, makes databases consistent most of the time, etc.

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.

查看更多
登录 后发表回答