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

Pat*_*ttu 11 c++ linux boost mmap external-sorting

我有一个非常大的文本文件(45GB).文本文件的每一行包含两个空格分隔的64位无符号整数,如下所示.

4624996948753406865 10214715013130414417

4305027007407867230 4569406367070518418

10817905656952544704 3697712211731468838 ......

我想读取文件并对数字执行一些操作.

我在C++中的代码:

void process_data(string str)
{
    vector<string> arr;
    boost::split(arr, str, boost::is_any_of(" \n"));
    do_some_operation(arr);
}

int main()
{
    unsigned long long int read_bytes = 45 * 1024 *1024;
    const char* fname = "input.txt";
    ifstream fin(fname, ios::in);
    char* memblock;

    while(!fin.eof())
    {
        memblock = new char[read_bytes];
        fin.read(memblock, read_bytes);
        string str(memblock);
        process_data(str);
        delete [] memblock;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我对c ++比较陌生.当我运行此代码时,我遇到了这些问题.

  1. 由于以字节读取文件,有时块的最后一行对应于原始文件中的未完成行("4624996948753406865 10214"而不是主文件的实际字符串"4624996948753406865 10214715013130414417").

  2. 这段代码运行得非常慢.在具有6GB RAM的64位Intel Core i7 920系统中运行一个块操作需要大约6秒.是否有任何可用于改善运行时的优化技术?

  3. 是否有必要在boost分割功能中包含"\n"和空白字符?

我已经阅读了关于C++中的mmap文件,但我不确定这是否是正确的方法.如果是,请附上一些链接.

seh*_*ehe 16

我重新设计了这个以进行流式传输而不是块.

一种更简单的方法是:

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

如果你大致知道预期有多少值​​,那么预先使用std::vector::reserve可以进一步提高速度.


或者,您可以使用内存映射文件并迭代字符序列.

更新我修改了上面的程序来解析uint32_t为一个向量.

当使用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
Run Code Online (Sandbox Code Playgroud)

当然它至少分配402653184*4*byte = 1.5 gibibytes.因此,当您读取45 GB文件时,您需要估计15 GiB的RAM来存储向量(假设重新分配时没有碎片):45GiB解析在10分45秒内完成:

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
Run Code Online (Sandbox Code Playgroud)

相比之下,只需运行wc -l 45gib_uint32s.txt大约需要12分钟(尽管没有实时优先级安排).wc非常

完整代码用于基准测试

#include <boost/spirit/include/qi.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <chrono>

namespace qi = boost::spirit::qi;

typedef std::vector<uint32_t> data_t;

using hrclock = std::chrono::high_resolution_clock;

int main(int argc, char** argv) {
    if (argc<2) return 255;
    data_t data;
    data.reserve(4392580288);   // for the  45 GiB file benchmark
    // data.reserve(402653284); // for the 4.5 GiB file benchmark

    boost::iostreams::mapped_file mmap(argv[1], boost::iostreams::mapped_file::readonly);
    auto f = mmap.const_data();
    auto l = f + mmap.size();

    using namespace qi;

    auto start_parse = hrclock::now();
    bool ok = phrase_parse(f,l,int_parser<uint32_t, 10>() % eol, blank, data);
    auto stop_time = hrclock::now();

    if (ok)   
        std::cout << "Parse success\n";
    else 
        std::cerr << "Parse failed at #" << std::distance(mmap.const_data(), f) << " around '" << std::string(f,f+50) << "'\n";

    if (f!=l) 
        std::cerr << "Trailing unparsed: " << std::distance(f,l) << " characters\n";

    std::cout << "Data.size():   " << data.size() << "\n";
    std::cout << "Time taken by parsing: " << std::chrono::duration_cast<std::chrono::milliseconds>(stop_time-start_parse).count() / 1000.0 << "s\n";
}
Run Code Online (Sandbox Code Playgroud)

[1]生成od -t u4 /dev/urandom -A none -v -w4 | pv | dd bs=1M count=$((9*1024/2)) iflag=fullblock > smaller.txt

[2]显然,这是将文件缓存在linux上的缓冲区缓存中 - 大文件没有这个好处