繁体   English   中英

缓冲输入与标准输入

[英]Buffered input versus standard input

我试图从输入文件中读取一长串数字(大约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;
}

第二个将需要将文件的内存大小增加一倍,否则,由于它在一次调用中读取了整个文件,因此它很可能将数据读取到内存中的速度与基础存储所能提供的速度一样快,然后将其处理速度与CPU可以这样做。

最好避免使用内存,在这方面,您的第一个程序更好。 在我的系统上,使用名为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保持“同步”。 请参阅此出色的答案,以获得良好的解释。 为了对其进行缓冲,我在第一个程序的顶部添加了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

(请注意:时间不定,我只进行了几次测试,但c似乎至少与b一样快。)

您的第二个程序运行很快,因为虽然没有缓冲,但我们只能发出一个读调用。 第一个程序必须对每个cin >>发出读取调用,而第三个程序可以缓冲(不时发出读取调用)。

请注意,添加这一行意味着您无法使用该名称的C FILE *stdin进行读取,也无法调用将这样做的任何库方法。 实际上,这可能不是问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM