逐行改进C的阅读文件?

前端之家收集整理的这篇文章主要介绍了逐行改进C的阅读文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在解析一个~500GB的日志文件,我的C版需要3.5分钟,而我的Go版需要1.2分钟.

我正在使用C的流来流式传输文件的每一行进行解析.

  1. #include <fstream>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. int main( int argc,char** argv ) {
  6. int linecount = 0 ;
  7. std::string line ;
  8. std::ifstream infile( argv[ 1 ] ) ;
  9. if ( infile ) {
  10. while ( getline( infile,line ) ) {
  11. linecount++ ;
  12. }
  13. std::cout << linecount << ": " << line << '\n' ;
  14. }
  15. infile.close( ) ;
  16. return 0 ;
  17. }

首先,为什么使用这段代码这么慢?
其次,我如何改进它以使其更快?

解决方法

众所周知,C标准库iostream很慢,标准库的所有不同实现都是这种情况.为什么?因为该标准对实施提出了许多要求,这些要求会抑制最佳性能.标准库的这一部分大约在20年前设计,在高性能基准测试中并不具备真正的竞争力.

你怎么能避免它?使用其他库来实现高性能异步I / O,例如boost asio或操作系统提供的本机功能.

如果你想保持在标准范围内,functionstd :: basic_istream :: read()可以满足你的性能需求.但在这种情况下,你必须自己进行缓冲和计数.这是如何做到的.

  1. #include <algorithm>
  2. #include <fstream>
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. int main( int,char** argv ) {
  7. int linecount = 1 ;
  8. std::vector<char> buffer;
  9. buffer.resize(1000000); // buffer of 1MB size
  10. std::ifstream infile( argv[ 1 ] ) ;
  11. while (infile)
  12. {
  13. infile.read( buffer.data(),buffer.size() );
  14. linecount += std::count( buffer.begin(),buffer.begin() + infile.gcount(),'\n' );
  15. }
  16. std::cout << "linecount: " << linecount << '\n' ;
  17. return 0 ;
  18. }

让我知道,如果它更快!

猜你在找的C&C++相关文章