【发布时间】:2011-07-04 00:51:07
【问题描述】:
我尝试打印Hello World 200,000 次,但我花了很长时间,所以我不得不停下来。但是在我添加一个char 数组作为缓冲区之后,只用了不到 10 秒。为什么?
添加缓冲区之前:
#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;
}
这是在添加缓冲区之后:
#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 读取文件有什么好处?
【问题讨论】:
-
基本上写一次 20 个元素比写一个元素 20 次要快。