本文介绍了为什么在C ++中缓冲很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打印 Hello World 200,000次,这花了我一辈子,所以我不得不停下来。但是,在我添加一个 char 数组作为缓冲区之后,花了不到10秒的时间。为什么?

I tried to print Hello World 200,000 times and it took me forever, so I have to stop. But right after I add a char array to act as a buffer, it took less than 10 seconds. Why?

在添加缓冲区之前:

#include <iostream>
using namespace std;

int main() {
        int count = 0;
        std::ios_base::sync_with_stdio(false);
        for(int i = 1; i < 200000; i++)
        {
                cout << "Hello world!\n";
                count++;
        }
                cout<<"Count:%d\n"<<count;
return 0;
}

这是在添加缓冲区之后:

And this is after adding a buffer:

#include <iostream>
using namespace std;

int main() {
        int count = 0;
        std::ios_base::sync_with_stdio(false);
        char buffer[1024];
        cout.rdbuf()->pubsetbuf(buffer, 1024);
        for(int i = 1; i < 200000; i++)
        {
                cout << "Hello world!\n";
                count++;
        }
                cout<<"Count:%d\n"<<count;
return 0;
}

这使我想到了Java。使用BufferReader读取文件有什么好处?

This makes me think about Java. What's the advantages of a using BufferReader to read in file?

推荐答案

对于文件操作,写入内存(RAM)总是比直接写入磁盘上的文件要快。

For the stand of file operations, writing to memory (RAM) is always faster than writing to the file on the disk directly.

为说明起见,我们定义:

For illustration, let's define:


  • 每个将IO操作写入文件磁盘上的成本为1毫秒

  • 每个通过网络将IO写入磁盘上文件的成本为5毫秒

  • 每个对磁盘的写入IO操作内存成本为0.5毫秒

假设我们必须将一些数据写入文件100次。

Let's say we have to write some data to a file 100 times.

100 times x 1 ms = 100 ms



案例2:直接通过网络在磁盘上写入文件



Case 2: Directly Writing to File On Disk Over Network

100 times x 5 ms = 500 ms



情况3 :在写入磁盘文件之前在内存中进行缓冲



Case 3: Buffering in Memory before Writing to File on Disk

(100 times x 0.5 ms) + 1 ms = 51 ms



案例4:在通过网络写入磁盘文件之前在内存中进行缓冲



Case 4: Buffering in Memory before Writing to File on Disk Over Network

(100 times x 0.5 ms) + 5 ms = 55 ms



骗局包含



内存中的缓冲总是比直接操作更快。但是,如果您的系统内存不足并且必须与页面文件交换,它将再次变慢。因此,您必须在内存和磁盘/网络之间平衡IO操作。

Conclusion

Buffering in memory is always faster than direct operation. However if your system is low on memory and has to swap with page file, it'll be slow again. Thus you have to balance your IO operations between memory and disk/network.

这篇关于为什么在C ++中缓冲很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:26