我有一个非常大的文本文件(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;
}

我对 C++ 比较陌生。当我运行这段代码时,我面临着这些问题。
  • 因为以字节为单位读取文件,有时一个块的最后一行对应原始文件中未完成的行(“4624996948753406865 10214”而不是实际的字符串“46249969487534062134711513471714068717140696875340621347171471406213471714140134753406213471714141475340613471141141753406134711411412121334114122133411412213341141)。
  • 这段代码运行非常非常慢。在具有 6GB RAM 的 64 位 Intel Core i7 920 系统中运行一个块操作大约需要 6 秒。是否有任何优化技术可以用来改进运行时?
  • 是否有必要在 boost split 函数中包含“\n”和空白字符?

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

    最佳答案

    我会重新设计它以进行流式传输,而不是在块上。

    一个更简单的方法是:

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

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

    或者,您可以使用内存映射文件并遍历字符序列。
  • How to parse space-separated floats in C++ quickly? 显示了这些方法和浮点数基准。

  • 更新 我修改了上面的程序,将 uint32_t s 解析成一个 vector 。

    使用 4.5GiB 的示例输入文件时 [1] 程序运行 9 秒 [2] 0x251819412:3411
    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 * byte = 1.5 Gibibytes。所以当
    你读了一个 45 GB 的文件,你估计需要 15GiB 的 RAM 来存储
    vector (假设重新分配时没有碎片): 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
    

    相比之下,仅运行 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";
    }
    

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

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

    关于c++ - 在 C++ 中有效地读取一个非常大的文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26736742/

    10-14 13:23
    查看更多