逐行改进C++的读取文件?

Improving C++'s reading file line by line?

本文关键字:读取 文件 C++ 逐行      更新时间:2023-10-16

我正在解析一个约500GB的日志文件,我的C++版本需要3.5分钟,我的Go版本需要1.2分钟。

我使用C++的流来流式传输要解析的文件的每一行。

#include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
   int linecount = 0 ;
   std::string line ;
   std::ifstream infile( argv[ 1 ] ) ;
   if ( infile ) {
      while ( getline( infile , line ) ) {
          linecount++ ;
      }
      std::cout << linecount << ": " << line << 'n' ;
   }
   infile.close( ) ;
   return 0 ;
}

首先,为什么使用此代码如此缓慢?第二,我如何改进它,使它更快?

众所周知,C++标准库iostreams的速度很慢,标准库的所有不同实现都是如此。为什么?因为该标准对实现提出了许多要求,这些要求阻碍了最佳性能。标准库的这一部分是大约20年前设计的,在高性能基准测试方面并没有真正的竞争力。

你怎样才能避免它?使用其他库进行高性能异步I/O,如boost asio或操作系统提供的本机函数。

如果您想保持在标准范围内,函数std::basic_istream::read()可以满足您的性能要求。但在这种情况下,你必须自己进行缓冲和行计数。以下是如何做到这一点。

#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
int main( int, char** argv ) {
   int linecount = 1 ;
   std::vector<char> buffer;
   buffer.resize(1000000); // buffer of 1MB size
   std::ifstream infile( argv[ 1 ] ) ;
   while (infile)
   {
       infile.read( buffer.data(), buffer.size() );
       linecount += std::count( buffer.begin(), 
                                buffer.begin() + infile.gcount(), 'n' );
   }
   std::cout << "linecount: " << linecount << 'n' ;
   return 0 ;
}

让我知道,如果它更快!

基于@Ralph Tandetzky的回答,但深入到低级的C IO功能,并假设Linux平台使用的文件系统提供了良好的直接IO支持(但保持单线程):

#define BUFSIZE ( 1024UL * 1024UL )
int main( int argc, char **argv )
{
    // use direct IO - the page cache only slows this down
    int fd = ::open( argv[ 1 ], O_RDONLY | O_DIRECT );
    // Direct IO needs page-aligned memory
    char *buffer = ( char * ) ::valloc( BUFSIZE );
    size_t newlines = 0UL;
    // avoid any conditional checks in the loop - have to
    // check the return value from read() anyway, so use that
    // to break the loop explicitly
    for ( ;; )
    {
        ssize_t bytes_read = ::read( fd, buffer, BUFSIZE );
        if ( bytes_read <= ( ssize_t ) 0L )
        {
            break;
        }
        // I'm guessing here that computing a boolean-style
        // result and adding it without an if statement
        // is faster - might be wrong.  Try benchmarking
        // both ways to be sure.
        for ( size_t ii = 0; ii < bytes_read; ii++ )
        {
            newlines += ( buffer[ ii ] == 'n' );
        }
    }
    ::close( fd );
    std::cout << "newlines:  " << newlines << endl;
    return( 0 );
}

如果你真的需要更快,可以使用多个线程来读取和计算换行符,这样你就可以在计算换行符的同时读取数据。但是,如果你不是在为高性能而设计的真正快速的硬件上运行,这就太过分了。

旧的好C的I/O例程应该比笨拙的C++流快得多。如果您知道所有行长度的合理上限,则可以使用fgets和类似char line[1<<20];的缓冲区。由于您将实际解析数据,因此您可能希望直接从文件中使用fscanf

请注意,如果您的文件物理存储在硬盘驱动器上,那么硬盘驱动器的读取速度无论如何都会成为瓶颈,如这里所述。这就是为什么您实际上不需要最快的CPU端解析来最小化处理时间,也许简单的fscanf就足够了。