我正在解析大约 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 ;
}
如果更快的话请告诉我!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)