jim*_*pez 7 c++ performance file-io
我正在解析一个~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 ;
}
Run Code Online (Sandbox Code Playgroud)
首先,为什么使用这段代码这么慢?其次,我如何改进它以使其更快?
Ral*_*zky 12
iostreams众所周知,C++标准库很慢,标准库的所有不同实现都是这种情况.为什么?因为该标准对实施提出了许多要求,这些要求会抑制最佳性能.标准库的这一部分大约在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 ;
}
Run Code Online (Sandbox Code Playgroud)
让我知道,如果它更快!
基于@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 );
}
Run Code Online (Sandbox Code Playgroud)
如果您确实需要更快,请使用多个线程来读取和计算换行符,这样您就可以在计算换行符的同时读取数据。但是,如果您不是在专为高性能而设计的非常快的硬件上运行,那么这就有点矫枉过正了。