我将对其进行重新设计以充当流式传输,而不是在一个块上。
std::ifstream ifs("input.txt");
std::vector<uint64_t> parsed(std::istream_iterator<uint64_t>(ifs), {});
如果您大致知道期望多少个值,那么预先使用std::vector::reserve
它可以进一步加快速度。
另外,您可以使用内存映射文件并遍历字符序列。
我修改了上面的程序以将uint32_t
s 解析为向量。
使用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
是