【发布时间】:2014-07-24 07:23:54
【问题描述】:
我试图从输入文件中读取一长串数字(大约 10^7)。通过一些搜索,我发现使用缓冲区读取内容与逐个读取数字相比具有更高的性能。
我的第二个程序比第一个程序执行得更好。我在第一个程序中使用 cin 流对象,在第二个程序中使用 stringstream 对象。这两者在 I/O 性能方面有什么区别?
#include <iostream>
using namespace std;
int main()
{
int n,k;
cin >> n >> k;
int count = 0;
while ( n-- > 0 )
{
int num;
cin >> num;
if( num % k == 0 )
count++;
}
cout << count << endl;
return 0;
}
与以下使用缓冲输入的代码相比,此程序需要更长的时间。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
cin.seekg(0, cin.end);
int length = cin.tellg();
cin.seekg(0, cin.beg);
char *buffer = new char[length];
cin.read(buffer,length);
stringstream ss(buffer);
int n,k;
ss >> n >> k;
int result = 0;
while( n-- )
{
int num;
ss >> num;
if( num % k == 0 )
result++;
}
cout << result << endl;
return 0;
}
【问题讨论】:
-
你知道
cin被缓冲了吗?而且cin(作为一个文件)有一个不确定的大小(所以寻找到最后是行不通的,因为没有真正的结束)。 -
我试图从文件 program.exe
-
输入来自哪里并不重要,
cin不是文件流,所以你不能真正改变位置。一旦从cin读取输入,您就不能倒带查看历史,也不能快进到未来。不要将cin视为文件,因为它不是。std::cin不能用于随机访问读取,即使您从重定向文件获取输入。 -
那么从键盘读取大量数字的最佳方法是什么?
-
@JoachimPileborg
cin实际上是 a little special about buffering。