我正在解析一个~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标准库iostream很慢,标准库的所有不同实现都是这种情况.为什么?因为该标准对实施提出了许多要求,这些要求会抑制最佳性能.标准库的这一部分大约在20年前设计,在高性能基准测试中并不具备真正的竞争力.
你怎么能避免它?使用其他库来实现高性能异步I / O,例如boost asio或操作系统提供的本机功能.
如果你想保持在标准范围内,functionstd :: 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 ;
- }
让我知道,如果它更快!