2

I am solving some problem and was testing with sample test case which prints 2*106 integers.

On initial run, I used cout<<ans; and it took 0.602sfor giving output.

I realized that I wasn't printing each output in a new line. So changed it to cout<<ans<<endl;. This time it took 2.052s!

Why does just printing a new line character after each line takes so long time?

vinayawsm
  • 845
  • 9
  • 28
  • Because it causes flushing: http://stackoverflow.com/a/29701830/1938163 – Marco A. May 12 '15 at 15:10
  • 1
    Flushing is by far the primary issue. A much smaller secondary effect, which is not covered in the other question, is that, depending on your platform, a "newline" may not be as simple as just another character. On some platforms it may be multiple characters. On a record-oriented filesystem, it might be an update to an on-disk data structure that contains the length of the line you just ended. – Adrian McCarthy May 12 '15 at 15:42

0 Answers0