加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

逐行改进C的阅读文件?

发布时间:2020-12-16 04:51:18 所属栏目:百科 来源:网络整理
导读:我正在解析一个~500GB的日志文件,我的C版需要3.5分钟,而我的Go版需要1.2分钟. 我正在使用C的流来流式传输文件的每一行进行解析. #include fstream#include string#include iostreamint main( int argc,char** argv ) { int linecount = 0 ; std::string line
我正在解析一个~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 ;
}

让我知道,如果它更快!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读