ManticMoo.COM -> Jeff's Articles -> Programming Articles -> How to make reading from an input stream efficient in C++

How to make reading from an input stream efficient in C++

by Jeffrey P. Bigham

In this article, I'll explain a bit about why C++ streams can be somewhat slow and give advice about how you can speed up your programs. Note such trickery is not needed for the majority of programs, but really only matters if you're reading a lot of data and need to do it quickly. That said, the speedup can be quite dramatic - can sometimes decrease the time required to read by almost 2 times - so it can definitely be worth it.

Unsync C++ Streams with stdio

C++ and C both have their own ways of doing I/O and unfortunately, they're not immediately compatible and what's really odd is that keeping them in line with one another can cause horrible inefficiencies. To get around this tell your programs not to sync C++ and C I/O like this:


ios_base::sync_with_stdio(false);

Be warned, however, that doing this will really unsync C's I/O so you shouldn't use C's I/O elsewhere in your program after using this line.

Previously, I wrote how to read lines from stdin in C++, and so now I update the sample program that I offered there with this one, which will do so more efficiently:


/////////////////////////////////
// efficient stdin input example
// using cin.getline
/////////////////////////////////

#include <iostream>
#include <string>

using namespace std;

int main() {
  string input_line;

  //  Don't sync C++ and C I/O
  ios_base::sync_with_stdio(false);
  while(cin) {
    getline(cin, input_line);
    cout << input_line << endl;
  }

  return 0;
}

Compile with Optimization


% g++ -o stdin_test -O3 stdin_test.cpp

ManticMoo.COM -> Jeff's Articles -> Programming Articles -> How to make reading from an input stream efficient in C++