I'm having trouble with I/O performance with cin and cout in C++. What can I do about it?

Modified on Sun, 21 Feb 2021 at 07:59 PM

There are at least three simple things that you can do with cin and cout in order to make your I/O experience in
C++ faster. Be advised though, that whatever you do, using the Cstdio routines (e.g. scanf and printf) is still
likely to be faster.

One problem is that the cin and cout are synchronized with the C stdio functions. In order to disable this,
use

ios::sync_with_stdio(false);

Another problem is that cin and cout are tied, which means that as soon as you read from cin, cout
is flushed. While this may be desirable when running a program interactively, it slows things down, especially if there are many alternating reads and writes. In order to disable this, use the command 

cin.tie(NULL);

Also, be aware that sync_with_stdio() resets this setting, so make sure you do things in the right order!

Third, it is good to know that the cout << endl also flushes cout. As far as we are aware of, this cannot be disabled, so if you are anticipating a lot of output, you should probably refrain from using endl, and use "\n" instead.


Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article