问题:在 C++ 中高效读取一个非常大的文本文件

我有一个非常大的文本文件(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++ 比较陌生。当我运行这段代码时,我遇到了这些问题。

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

2.这段代码运行非常非常慢。在具有 6GB RAM 的 64 位 Intel Core i7 920 系统中运行一个块操作大约需要 6 秒。有什么优化技术可以用来改善运行时间吗?

  1. boost split 函数中是否需要包含“\n”和空白字符?

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

解答

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

一个更简单的方法是:

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

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


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

  • 如何在 C++ 中快速解析空格分隔的浮点数? 展示了这些带有浮点基准的方法。

更新我修改了上面的程序,将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 * byte u003d 1.5 gibibytes。因此,当您读取 45 GB 文件时,您将需要估计 15GiB 的 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

相比之下,仅运行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 上的缓冲区缓存中的文件 - 大文件没有这个好处

Logo

更多推荐