- Retrieved from http://stackoverflow.com/a/9371717/ on April 13, 2017
- Posted by user Vaughn Cato on Feb 21 '12 at 3:24
cin is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:
Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the
iostreams often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:
int myvalue1; cin >> myvalue1; int myvalue2; scanf("%d",&myvalue2);
If more input was read by
cin than it actually needed, then the second integer value wouldn't be available for the
scanf function, which has its own independent buffer. This would lead to unexpected results.
To avoid this, by default, streams are synchronized with
stdio. One common way to achieve this is to have
cin read each character one at a time as needed using
stdio functions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn't a big problem, but when you are reading millions of lines, the performance penalty is significant.
Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the