C++ getline() 比 Java 的 readLine() 慢
C++ getline() slower than Java's readLine()
我试图读取一个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控制台太慢了,特别是在做终端仿真时,这一点都不有趣。
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- 当用户键入分隔符时,停止getline()输入
- getline() 的原型/库是什么;
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 错误:调用'getline'没有匹配函数
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将 getline() 与文件一起使用
- 我有三个 getline,但是一旦编译,输入就太多了
- 在 std::getline 和 std::cin 期间卡在循环中
- 为什么 getline() 不读取文本文件中的所有内容?
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- std::getline没有在while循环中重新请求用户输入
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- Getline(cin,str)的奇怪输出
- 我在C++中使用 getline() 函数时遇到问题
- 而循环跳过 cin.getline() 对于 C 字符串
- C++ getline() 比 Java 的 readLine() 慢
- C++ ifstream.getline() 明显比 Java 的 BufferedReader.readLine() 慢吗?