Thug life B| – Faster I/O in Competitive coding

Always prefer using cin/cout over scanf/printf. Reason?. Fairly obvious- too many characters to type :D.

People prefer scanf/printf because they are considered to be faster than cin/cout but what if I told you that there was a way by which you could use your favorite cin/cout without compromising much with the fast IO operation?

Enter – std::ios::sync_with_stdio(0)

This statement generally de-synchronizes the backward compatibility of C++ with C. To be exact, this function de-synchronizes IO methods like printf with cout and scanf with cin, saving a lot of function call overhead. This results in cin/cout being almost as fast as printf/scanf.

So what are the stakes?

De-synchronizing them will in turn cause “non-periodic” flushing of output/input into buffer streams. For example if you use this snippet of code.

What output do you expect?

“ap ac” I hear?

No!

“ac ap”. Compile it and you’ll know.

What happened? This is where synchronization of stdio and cin/cout came into play. As a result of std::ios::sync_with_stdio(0), the output of cout was flushed before printf. This mismatching of IO streams is the reason why you should never use printf/scanf and cin/cout together while using std::ios::sync_with_stdio(0). (In competitive coding I scored over 50 WAs to realize this “minor” mistake).

Enter- cin.tie(NULL)/cout.tie(NULL)

Though using these functions won’t affect the time consumption of your program drastically but getting acquainted with them is definitely worth it.

“tie” function generally “ties” cin and cout together, which means that in console the program will always flush IO streams in the order of their appearance in the code and not mix things up. If “tie” is disabled IO buffers will flush randomly, but this will save some overhead time used to “tie” cin/cout together.

So what are the stakes?

“untying” cin/cout would only effect your console IO, you might get random console prints. But if you are reading input from a file (which is exactly what competitive coding sites do) and flushing output into another file, in that case you can “untie” cin/cout safely.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s