我试图从输入文件中读取一长串数字(大约10^7)。通过一些搜索,我发现使用缓冲区读取内容比逐个读取内容具有更高的性能。
我的第二个节目比第一个节目表现得更好。我在第一个程序中使用一个cin流对象,在第二个程序中使用stream流对象。这两者在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;
}发布于 2014-07-24 08:12:36
第二个文件在内存中需要文件大小的两倍,否则,由于它在一个调用中读取整个文件,它很可能会以底层存储所能满足的速度将数据读入内存,然后尽可能快地处理它。
最好避免内存开销,在这方面,您的第一个程序更好。在我的系统中,使用一个名为test.txt的输入,该输入如下所示:
10000000 2
13
13
< 10000000-2 more "13"s. >你的第一个程序叫做a,第二个叫做b。我得到:
% time ./a <test.txt
0
./a < test.txt 1.70s user 0.01s system 99% cpu 1.709 total
% time ./b <test.txt
0
./b < test.txt 0.76s user 0.04s system 100% cpu 0.806 total默认情况下,cin不会被缓冲,以保持与stdio的“同步”。有关一个很好的解释,请参见this excellent answer。为了使其缓冲,我将cin.sync_with_stdio(false)添加到您的第一个程序的顶部,并调用结果c,它的运行速度可能稍微快一些:
% time ./c <test.txt
0
./c < test.txt 0.72s user 0.01s system 100% cpu 0.722 total(注意:“泰晤士报”( times )在这段时间里只运行了几个测试,但c似乎至少和b一样快。)
您的第二个程序运行迅速,因为虽然没有缓冲,我们只需发出一个读取调用。第一个程序必须为每个cin >>发出一个读调用,而第三个程序可以缓冲(不时发出读调用)。
请注意,添加这一行意味着您不能使用这个名称从stdin中读取C FILE *,也不能调用任何这样做的库方法。在实践中,这可能不是一个问题。
https://stackoverflow.com/questions/24927459
复制相似问题