【发布时间】:2018-06-16 18:18:54
【问题描述】:
我有一个 2GB 的文件。平均一行有 15 个字符(最多 50 个)。使用时:
#include <iostream>
#include <fstream>
#include <string>
void main()
{
std::ifstream input("myfile.txt");
std::string line;
while (std::getline(input, line))
{
}
return;
}
大约需要 320 秒,而这段 Python 代码:
with open('myfile.txt', mode='r') as f:
for l in f:
semicolonpresent = ';' in l # do anything here, not important
不到一分钟。
我使用的 C++ 版本有什么问题?
注意:我已经尝试了很多次,每次都在重新启动之后,或者在之前的多次运行之后(所以它可能在 I/O 缓存中),但我总是得到这样的数量级。
注意 2:我在 Windows 7/64 上编译了 C++ 代码,使用:
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86
cl main.cpp
【问题讨论】:
-
你编译时是否开启了优化?
-
@Galik 我用编译行编辑了问题
-
cl main.cpp缺少编译器可以使用的大多数花哨的参数。您最好使用默认的 VS 控制台应用程序模板创建程序。并且在构建时不要忘记选择Release配置。 -
@VTT
nobody really uses iostreams to read files in C++然后我误解了stackoverflow.com/questions/7868936/read-file-line-by-line/…。你将如何在 C++ 中逐行读取一个大文件? -
我的意思是没有人真正在现实生活中使用它们,并不是说它们根本不能用。例如,请参阅What serious alternatives exist for the IOStream library。 C++ 中缺乏适当的 io 例程是一个严重的语言缺陷,迫使开发人员寻找替代方案。不幸的是,标准委员会忙于添加诸如表情符号语法或黎曼 zeta 函数之类的东西。我会使用自制的 mmap 或异步读取包装器。