When does cout flush?
Asked Answered
A

1

10

I know endl or calling flush() will flush it. I also know that when you call cin after cout, it flushes too. And also when the program exit. Are there other situations that cout flushes?

I just wrote a simple loop, and I didn't flush it, but I can see it being printed to the screen. Why? Thanks!

for (int i =0; i<399999; i++) {

        cout<<i<<"\n";

}

Also the time for it to finish is same as withendl both about 7 seconds.

for (int i =0; i<399999; i++) {

        cout<<i<<endl;

}
Aggri answered 12/3, 2014 at 7:56 Comment(1)
It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout. Most CRTs have an isatty() helper function that is used to determine whether automatic flushing is required.Paralyse
M
8

There is no strict rule by the standard - only that endl WILL flush, but the implementation may flush at any time it "likes".

And of course, the sum of all digits in under 400K is 6 * 400K = 2.4MB, and that's very unlikely to fit in the buffer, and the loop is fast enough to run that you won't notice if it takes a while between each output. Try something like this:

 for(int i = 0; i < 100; i++)
 {
   cout<<i<<"\n";
   Sleep(1000);
 }

(If you are using a Unix based OS, use sleep(1) instead - or add a loop that takes some time, etc)

Edit: It should be noted that this is not guaranteed to show any difference. I know that on my Linux machine, if you don't have a flush in this particular type of scenario, it doesn't output anything - however, some systems may do "flush on \n" or something similar.

Mousey answered 12/3, 2014 at 8:5 Comment(3)
How about the time I measured? Shouldn't the one without endl be faster even though sometimes it flushes, it should flush less often right? I tried your code, it's great. Thanks!Aggri
It is highly likely overtaken by the time it actually takes to output to the screen. If you send the output to NUL: or some such, you may well see a small difference (but 400k numbers is probably not enough for that - try a few million).Mousey
"overtaken" = "dominated by".Mousey

© 2022 - 2024 — McMap. All rights reserved.