逐行改进C++的读取文件?
Improving C++'s reading file line by 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++标准库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 ;
}
让我知道,如果它更快!
基于@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 );
}
如果你真的需要更快,可以使用多个线程来读取和计算换行符,这样你就可以在计算换行符的同时读取数据。但是,如果你不是在为高性能而设计的真正快速的硬件上运行,这就太过分了。
旧的好C的I/O例程应该比笨拙的C++流快得多。如果您知道所有行长度的合理上限,则可以使用fgets
和类似char line[1<<20];
的缓冲区。由于您将实际解析数据,因此您可能希望直接从文件中使用fscanf
。
请注意,如果您的文件物理存储在硬盘驱动器上,那么硬盘驱动器的读取速度无论如何都会成为瓶颈,如这里所述。这就是为什么您实际上不需要最快的CPU端解析来最小化处理时间,也许简单的fscanf
就足够了。
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中