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

查看:21
本文介绍了缓冲与非缓冲 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天全站免登陆