Fast I/O for Competitive Programming
Basically cin/cout can outperform printf/scanf provided, that some optimisation are turned on. Otherwise major slow down can be expected. - Yet again on C++ input/output
ios_base::sync_with_stdio(false)
Enabled by placing this line in the beginning of the program, before any input/output.
This command turns off iostreams and stdio synchronization (description). It is on by default, which means that calls to iostreams and stdio functions can be freely interleaved even for the same underlying stream. When synchronization is turned off, mixing calls is no longer allowed, but iostreams can potentially operate faster.
cin.tie(nullptr)
By default, cin is tied to cout, which means that cout is flushed before any operation on cin. Turning this feature off allows iostreams, again, to operate faster. One should be careful with this optimization in interactive problems: it should either not be used, or an explicit flush should be issued each time.
endl
vs “\n” vs std::flush
Frequent use of endl also negatively affects iostreams performance, because endl
not only outputs a newline character, but also flushes the stream’s buffer. You can simply output '\n'
or "\n"
instead of endl
.
std::getline()
&& cin.ignore()
Streams pretty well know to be very slow. It is not a big surprise though - they need to handle localizations, conditions etc. One possible solution would be to read file line by line by std::getline( std:::cin, str )
and convert string to numbers yourself.
cout.tie(nullptr)
/ SO
On some system cerr may be tie to cout.
std::unitbuf
cerr
has unitbuf set by default, so it will be flushed at the end of every <<
operator.
see also
- Which is the fastest method of input in C++
- C++ fastest cin for reading stdin?
- The Standard Librarian: IOStreams and Stdio
- Using scanf() in C++ programs is faster than using cin?
- Fast I/O for Competitive Programming
- All efficient input taking and fast I/O techniques in C++
- Why You Shouldn’t Use std::endl