C++ getline() 比 Java 的 readLine() 慢

C++ getline() slower than Java's readLine()

本文关键字:readLine getline C++ Java      更新时间:2023-10-16

我试图读取一个250K行的文件,并对每一行应用正则表达式。然而,代码比Java的readline函数慢得多。在Java中,所有的解析大约在10秒内完成,而在c++中则需要2分钟以上。我看到c++的ifstream.getline()比java的BufferedReader.readLine()慢得多。并在main:

上面添加了这两行
std::ifstream::sync_with_stdio(false);
std::ios::sync_with_stdio(false);

其余代码(我简化了它以消除regex可能引起的任何延迟):

#include "stdafx.h"
#include <ios>
#include <string>
#include <fstream>
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    std::string libraryFile = "H:\library.txt";
    std::ios::sync_with_stdio(false);
    std::string line;
    int i = 1;
    std::ifstream file(libraryFile);
    while (std::getline (file, line)) {
        std::cout << "rStored " << i++ << " lines.";
    }
    return 0;
}

这个例子看起来很简单,但即使在大多数帖子中建议的修复似乎也不起作用。我在VS2012中使用发布设置多次运行。exe,但我无法达到Java的时间。

速度慢是由几个原因引起的。

  • 混合cout和cin: c++ IO库必须在每次使用cin时同步cout。这是为了确保在请求输入之前显示输入提示之类的内容。

  • 使用Windows控制台输出:Windows控制台太慢了,特别是在做终端仿真时,这一点都不有趣。