1

我正在尝试读取 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);

其余代码(我简化它以消除正则表达式可能导致的任何延迟):

#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 的时代。

4

1 回答 1

5

缓慢是由几件事引起的。

  • 混合 cout 和 cin:C++ IO 库必须在每次使用 cin 时同步 cout。这是为了确保在要求输入之前显示输入提示等内容。这真的很伤缓冲。

  • 使用 Windows 控制台输出:Windows 控制台非常慢,尤其是在进行终端仿真时,这并不好笑。如果可能的话输出到文件。

于 2013-06-18T16:24:17.977 回答