您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在C ++中有效读取非常大的文本文件

在C ++中有效读取非常大的文本文件

我将对其进行重新设计以充当流式传输,而不是在一个块上。

一个更简单的方法是:

std::ifstream ifs("input.txt");
std::vector<uint64_t> parsed(std::istream_iterator<uint64_t>(ifs), {});

如果您大致知道期望多少个值,那么预先使用std::vector::reserve它可以进一步加快速度。

另外,您可以使用内存映射文件并遍历字符序列。

修改了上面的程序以将uint32_ts 解析为向量。

使用4.5GiB 的样本输入文件时,程序将在9秒 内运行:

sehe@desktop:/tmp$ make -B && sudo chrt -f 99 /usr/bin/time -f "%E elapsed, %c context switches" ./test smaller.txt
g++ -std=c++0x -Wall -pedantic -g -O2 -march=native test.cpp -o test -lboost_system -lboost_iostreams -ltcmalloc
parse success
trailing unparsed: '
'
data.size():   402653184
0:08.96 elapsed, 6 context switches

当然,它至少分配402653184 * 4 字节= 1.5吉字节。因此,当您读取一个45 GB的文件时,您将需要大约15GiB的RAM来存储矢量(假设重新分配时没有碎片): 45GiB解析在45分钟内完成10分钟* :

make && sudo chrt -f 99 /usr/bin/time -f "%E elapsed, %c context switches" ./test 45gib_uint32s.txt 
make: Nothing to be done for `all'.
tcmalloc: large alloc 17570324480 bytes == 0x2cb6000 @  0x7ffe6b81dd9c 0x7ffe6b83dae9 0x401320 0x7ffe6af4cec5 0x40176f (nil)
Parse success
Trailing unparsed: 1 characters
Data.size():   4026531840
Time taken by parsing: 644.64s
10:45.96 elapsed, 42 context switches

相比之下,仅运行wc -l 45gib_uint32s.txt就花费了大约12分钟(尽管没有实时优先级调度)。wc

其他 2022/1/1 18:22:29 有510人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶