2

I'm trying to understand what is the motivation for buffering the print to standard output.

I've experienced this in multiple programming languages, a scenario where you're trying to trace a bug by doing print outputs and your print statements aren't printed real time just because the buffer wasn't flushed.

So to get the command to be actually printed out where it's called and additional flush has to be used.

What is the motivation for such behavior?

TheMeaningfulEngineer
  • 951
  • 2
  • 10
  • 17

2 Answers2

3

Historically, to reduce delays in processing.

If you were writing to a line printer, for example, and each line wasn't buffered, then you had to wait until the entire line was printed before control returned from your Print function. This not only delayed further processing in your program, but it also slowed down printing because the printer had to wait for you to process it and send it a new line to print, after it was done printing the previous one.

Having a buffer meant that the printer could be printing while you're processing and preparing the next line to be printed.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
2

stdout is usually buffered in line-oriented way, except an application has an additional custom buffer. The reason is performance and that classic terminals work better in this fashion. Also imagine that someone used a printer for stdout and stdin was some input-only device (typically having only one line for input). You need a linefeed in this case to see the output on a printer.

But stdout should be always chronological (it's a FIFO, first in first out). What you perhaps see are applications that use threading or multiple processes. Some application developers are too lazy to implement proper locking mechanisms for stdout. stdout is like a multiplexer and may combine the outputs multiple outputs into one stream that looks garbled.

  • `But stdout should be always chronological` you're right, I've used the incorrect term, should of used `non real time` – TheMeaningfulEngineer Sep 09 '16 at 19:09
  • You can force instant feedback with flush, as you said. But you have more features when you flush manually on-demand. For example, some logs group lines ("... and 200 repeated lines"). If you force instant output, this won't make sense, because it's impossible without buffers. Especially for logs, lines are often considered units and not single characters. – Martin Sugioarto Sep 09 '16 at 19:22