在 C++ 中快速读取文本文件

问题描述 投票:0回答:6

我目前正在用 C++ 编写一个程序,其中包括读取大量大型文本文件。每个都有大约 400.000 行,在极端情况下每行有 4000 或更多字符。为了进行测试,我使用

ifstream
阅读了其中一个文件以及我在 cplusplus.com 上找到的实现。在我的机器上,大约需要 60 秒,考虑到我的工作流程,这个时间相当长了。有没有直接的方法可以提高阅读速度?

我使用的代码或多或少是这样的:

string tmpString;
ifstream txtFile(path);
if(txtFile.is_open())
{
    while(txtFile.good())
    {
        m_numLines++;
        getline(txtFile, tmpString);
    }
    txtFile.close();
}

备注:

  • 我读取的文件只有 ~80 MB 大。我提到每行的最大字符数为 4000,因为我认为可能有必要知道才能进行缓冲
  • 我必须使用
    readline
    ,因为我想计算行数
  • ifstream
    实例化为二进制并没有使读取速度更快
  • 并行化任务会加快速度,但并不直接,并且很有可能引入错误

经过多次来回讨论,非常感谢sehe投入这么多时间,我非常感激!

c++ performance io ifstream
6个回答
93
投票

更新:请务必检查初始答案下方的(令人惊讶的)更新


内存映射文件对我很有帮助1

#include <boost/iostreams/device/mapped_file.hpp> // for mmap
#include <algorithm>  // for std::find
#include <iostream>   // for std::cout
#include <cstring>

int main()
{
    boost::iostreams::mapped_file mmap("input.txt", boost::iostreams::mapped_file::readonly);
    auto f = mmap.const_data();
    auto l = f + mmap.size();

    uintmax_t m_numLines = 0;
    while (f && f!=l)
        if ((f = static_cast<const char*>(memchr(f, '\n', l-f))))
            m_numLines++, f++;

    std::cout << "m_numLines = " << m_numLines << "\n";
}

这应该相当快。

更新

如果它可以帮助您测试这种方法,这里有一个版本直接使用

mmap
而不是使用Boost:在Coliru上查看它

#include <algorithm>
#include <iostream>
#include <cstring>

// for mmap:
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

const char* map_file(const char* fname, size_t& length);

int main()
{
    size_t length;
    auto f = map_file("test.cpp", length);
    auto l = f + length;

    uintmax_t m_numLines = 0;
    while (f && f!=l)
        if ((f = static_cast<const char*>(memchr(f, '\n', l-f))))
            m_numLines++, f++;

    std::cout << "m_numLines = " << m_numLines << "\n";
}

void handle_error(const char* msg) {
    perror(msg); 
    exit(255);
}

const char* map_file(const char* fname, size_t& length)
{
    int fd = open(fname, O_RDONLY);
    if (fd == -1)
        handle_error("open");

    // obtain file size
    struct stat sb;
    if (fstat(fd, &sb) == -1)
        handle_error("fstat");

    length = sb.st_size;

    const char* addr = static_cast<const char*>(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0u));
    if (addr == MAP_FAILED)
        handle_error("mmap");

    // TODO close fd at some point in time, call munmap(...)
    return addr;
}

更新

通过查看 GNU coreutils 的源代码,我发现了我可以从中挤出的最后一点性能

wc
。令我惊讶的是,使用以下(大大简化的)改编自
wc
的代码,与上面的内存映射文件一起运行的时间约为 84%

static uintmax_t wc(char const *fname)
{
    static const auto BUFFER_SIZE = 16*1024;
    int fd = open(fname, O_RDONLY);
    if(fd == -1)
        handle_error("open");

    /* Advise the kernel of our access pattern.  */
    posix_fadvise(fd, 0, 0, 1);  // FDADVICE_SEQUENTIAL

    char buf[BUFFER_SIZE + 1];
    uintmax_t lines = 0;

    while(size_t bytes_read = read(fd, buf, BUFFER_SIZE))
    {
        if(bytes_read == (size_t)-1)
            handle_error("read failed");
        if (!bytes_read)
            break;

        for(char *p = buf; (p = (char*) memchr(p, '\n', (buf + bytes_read) - p)); ++p)
            ++lines;
    }

    return lines;
}

1 参见例如这里的基准:如何快速解析 C++ 中的空格分隔的浮点数?


12
投票

4000 * 400,000 = 1.6 GB 如果您的硬盘驱动器不是 SSD,您可能会获得约 100 MB/s 的顺序读取。仅 I/O 就需要 16 秒。

由于您没有详细说明您使用的具体代码或您需要如何解析这些文件(您是否需要逐行读取它,系统是否有大量RAM,您可以将整个文件读取到大RAM中吗?缓冲区然后解析它?)您几乎无法加快该过程。

按顺序读取文件时,内存映射文件不会提供任何性能改进。也许手动解析大块的新行而不是使用“getline”会提供改进。

编辑经过一些学习(感谢@sehe)。这是我可能会使用的内存映射解决方案。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>

int main() {
    char* fName = "big.txt";
    //
    struct stat sb;
    long cntr = 0;
    int fd, lineLen;
    char *data;
    char *line;
    // map the file
    fd = open(fName, O_RDONLY);
    fstat(fd, &sb);
    //// int pageSize;
    //// pageSize = getpagesize();
    //// data = mmap((caddr_t)0, pageSize, PROT_READ, MAP_PRIVATE, fd, pageSize);
    data = mmap((caddr_t)0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    line = data;
    // get lines
    while(cntr < sb.st_size) {
        lineLen = 0;
        line = data;
        // find the next line
        while(*data != '\n' && cntr < sb.st_size) {
            data++;
            cntr++;
            lineLen++;
        }
        /***** PROCESS LINE *****/
        // ... processLine(line, lineLen);
    }
    return 0;
}

12
投票

Neil Kirk,不幸的是我无法回复您的评论(没有足够的声誉),但我对 ifstream 和 stringstream 进行了性能测试,并且逐行读取文本文件的性能完全相同。

std::stringstream stream;
std::string line;
while(std::getline(stream, line)) {
}

对于 106MB 的文件,这需要 1426 毫秒。

std::ifstream stream;
std::string line;
while(ifstream.good()) {
    getline(stream, line);
}

同一文件需要 1433 毫秒。

下面的代码更快:

const int MAX_LENGTH = 524288;
char* line = new char[MAX_LENGTH];
while (iStream.getline(line, MAX_LENGTH) && strlen(line) > 0) {
}

同一文件需要 884 毫秒。 这只是有点棘手,因为您必须设置缓冲区的最大大小(即输入文件中每行的最大长度)。


5
投票

作为具有一点竞争性编程背景的人,我可以告诉你:至少对于像整数解析这样的简单事情,C 中的主要成本是锁定文件流(默认情况下是为多线程完成的)。请改用

unlocked_stdio
版本(
fgetc_unlocked()
fread_unlocked()
)。对于 C++,常见的做法是使用
std::ios::sync_with_stdio(false)
,但我不知道它是否和
unlocked_stdio
一样快。

这里是我的标准整数解析代码供参考。正如我所说,它比 scanf 快很多,主要是因为没有锁定流。对我来说,它和我以前使用过的最好的手工编码 mmap 或自定义缓冲版本一样快,而且没有疯狂的维护债务。 int readint(void) { int n, c; n = getchar_unlocked() - '0'; while ((c = getchar_unlocked()) > ' ') n = 10*n + c-'0'; return n; }

(注意:只有在任意两个整数之间恰好有一个非数字字符时,此方法才有效)。

当然,如果可能的话,避免内存分配...


3
投票

如果这样做,请考虑并行化操作。

无论哪种方式,请考虑使用二进制流,或对数据块进行无缓冲的

read


1
投票
Random file access

或使用

binary mode
。对于顺序,这很大,但仍然取决于您正在阅读的内容。
    

© www.soinside.com 2019 - 2024. All rights reserved.