C ++程序员应该经常使用std :: flush吗? [英] Should C++ programmers use std::flush frequently?

查看:583
本文介绍了C ++程序员应该经常使用std :: flush吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议C ++程序员经常写如

  std :: cout< output:< i<< 和< j<< std :: flush; 
//更多
std :: cout<< 结束换行。 << std :: endl; // endl does flush

换句话说,在没有 endl ,我们应该 flush

解决方案

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




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


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

    这篇关于C ++程序员应该经常使用std :: flush吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆