且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++程序员应该经常使用std :: flush吗?

更新时间:2023-11-12 11:47:58

你的平均程序不需要频繁的刷新。在一些情况下,刷新是更接近于特殊情况:




  • 与人类或其他系统交互:在等待输入之前刷新输出


  • 休眠一段时间:在延长睡眠或等待之前刷新会简化日志文件的检查,使大多数时间数据库保持一致等。 ul>

    如果不需要缓冲,***首先禁用缓冲,而不是引起大量刷新。



    大多数时候,程序通过启用缓冲区而受益。有时他们会在这里和那里产生一些字符。



    在我几十年的工程中,我最大的性能提升通常是通过改善缓冲来实现的。有时通过将大于512字节(默认)的默认 FILE 缓冲区大小增加到4K或32K(有时更高)。其他时候通过添加一层缓冲或缓存。通常,每次通过操作系统的i / o系统都会有很高的开销。减少系统调用的总数(通常)是一种简单而高效的方案来提高性能。


    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?

    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.