缓冲与无缓冲IO [英] Buffered vs unbuffered IO

查看:163
本文介绍了缓冲与无缓冲IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,默认情况下,程序中的I/O是经过缓冲的,即,它们是从临时存储提供给请求程序的. 我知道缓冲可以提高IO性能(也许通过减少系统调用).我已经看到了一些禁用缓冲的示例,例如C中的setvbuf.这两种模式之间有什么区别?何时应该在另一种模式下使用一种模式?

I learned that by default I/O in programs is buffered, i.e they are served from a temporary storage to the requesting program. I understand that buffering improves IO performance (maybe by reducing system calls). I have seen examples of disabling buffering, like setvbuf in C. What is the difference between the two modes and when should one be used over the other?

推荐答案

只要想确保在继续输出之前就已写入输出,就需要无缓冲的输出.一个示例是C运行时库下的标准错误-默认情况下,通常不缓冲此错误.由于(希望)很少发生错误,因此您想立即了解它们.另一方面,缓冲标准输出 只是因为它假定会有更多的数据通过它.

You want unbuffered output whenever you want to ensure that the output has been written before continuing. One example is standard error under a C runtime library - this is usually unbuffered by default. Since errors are (hopefully) infrequent, you want to know about them immediately. On the other hand, standard output is buffered simply because it's assumed there will be far more data going through it.

另一个示例是日志记录库.如果您的日志消息保存在进程的缓冲区中,并且进程转储了内核,则很有可能永远不会写入输出.

Another example is a logging library. If your log messages are held within buffers in your process, and your process dumps core, there a very good chance that output will never be written.

此外,不仅仅是最小化的系统调用,还包括磁盘I/O.假设某个程序一次读取一个字节的文件.使用无缓冲输入,即使每个字节可能都必须读取一个完整的块(磁盘硬件本身可能有缓冲区,但您仍要访问磁盘控制器),您仍将为每个字节访问(相对很慢)磁盘这将比内存访问慢).

In addition, it's not just system calls that are minimized but disk I/O as well. Let's say a program reads a file one byte at a time. With unbuffered input, you will go out to the (relatively very slow) disk for every byte even though it probably has to read in a whole block anyway (the disk hardware itself may have buffers but you're still going out to the disk controller which is going to be slower than in-memory access).

通过缓冲,整个块被立即读入缓冲区,然后将各个字节从(内存中,非常快的)缓冲区中传递给您.

By buffering, the whole block is read in to the buffer at once then the individual bytes are delivered to you from the (in-memory, incredibly fast) buffer area.

请记住,缓冲可以采用多种形式,例如以下示例:

Keep in mind that buffering can take many forms, such as in the following example:

+-------------------+-------------------+
| Process A         | Process B         |
+-------------------+-------------------+
| C runtime library | C runtime library | C RTL buffers
+-------------------+-------------------+
|               OS caches               | Operating system buffers
+---------------------------------------+
|      Disk controller hardware cache   | Disk hardware buffers
+---------------------------------------+
|                   Disk                |
+---------------------------------------+

这篇关于缓冲与无缓冲IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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