如何改进C++逐行读取文件的性能?

9
我正在解析一个约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 ;
}

首先,为什么使用这段代码会如此缓慢?其次,我该如何改进它以提高速度?


2
为什么使用这段代码很慢?首先再次测量,不使用std::cout部分 - 现在您正在测量文件I/O和打印到控制台。 - stijn
7
cout在循环外,不应该有影响。 - Dialecticus
2
当你说你正在“解析”一个文件时,你指的是什么?你所做的只是读取和计算行数吗? - Some programmer dude
2
这种问题受益于了解确切的C++实现。与Go不同,C++有多个独立的实现。 - MSalters
5
你尝试过使用 std::ios_base::sync_with_stdio(false); 吗?还有使用 std::cin.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); 并配合一个足够大的 char buffer[];。 - Tony Delroy
显示剩余7条评论
3个回答

12

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 ;
}

如果更快,请告诉我!


5

@Ralph Tandetzky答案的基础上,但是采用底层C IO函数,并假定使用提供良好直接IO支持的Linux平台文件系统(但仍保持单线程):

#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 );
}

如果你需要更快地读取和计算换行符,可以使用多个线程来读取和计算换行符,这样在计算换行符的同时也可以读取数据。但如果你的硬件不是专门用于高性能设计的超级快速硬件,这种方法可能有些过头了。

0

从旧好的 C 语言中的 I/O 程序应该比笨拙的 C++ 流快得多。如果您知道所有行的长度的合理上限,那么您可以使用 fgets 结合像 char line[1<<20] 这样的缓冲区。因为您要实际解析数据,所以您可能希望直接从文件中使用 fscanf

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接