小编典典
我将对其进行重新设计以充当流式传输,而不是在一个块上。
一个更简单的方法是:
std::ifstream ifs("input.txt");
std::vector parsed(std::istream_iterator(ifs), {});
如果您大致知道期望多少个值,那么预先使用std::vector::reserve它可以进一步加快速度。
另外,您可以使用内存映射文件并遍历字符序列。
更新 我修改了上面的程序以将uint32_ts 解析为向量。
使用4.5GiB [1] 的样本输入文件时,程序将在9秒 [2] 内运行:
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来存储矢量(假设重新分配时没有碎片)&#x