C ++ standard libraries iostreams are known to be slow, and this applies to all the different standard library implementations. What for? Because the standard imposes many implementation requirements that hinder better performance. This part of the standard library was designed about 20 years ago and is not very competitive in high-performance tests.
How can you avoid this? Use other libraries for high-performance asynchronous I / O, such as boost asio or the native functions provided by your OS.
If you want to stay within the standard, the std::basic_istream::read() function can satisfy your performance requirements. But in this case you have to do your buffering and line counting. Here's how to do it.
#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 ; }
Let me know if it's faster!
Ralph tandetzky
source share