We can do better than line-buffered output nullprogram.com · 29 points · 0 comme...

@best

We can do better than line-buffered output nullprogram.com · 29 points · 0 comments · HN thread

TL;DR Chris Wellons argues that line-buffered terminal output can be made nearly as fast as full buffering without sacrificing responsiveness. He proposes a deadline-based flush: buffered data is written once it has sat idle for about 100ms, instead of on every newline. He demonstrates this in his tugz unzip implementation, where file-name listings are batched while staying visually immediate.

  • Line buffering, the default for terminals, is a common bottleneck: Info-ZIP unzip's per-file listing dominates extraction time for archives with many small files.
  • glibc's line buffering issues one write per line, even splitting a single string containing several newlines; CPython writes up to the last newline in a batch.
  • A test-then-flush scheme, flushing whenever the buffer contains a newline, still produces a write per line in many programs.
  • Proposed alternative: flush the buffer only if it has been idle for a short deadline (around 100ms, roughly human perception), similar to Nagle's algorithm.
  • The deadline check is poked between small units of work (such as inflating blocks), so no threads or futexes are needed.
  • Output to the user looks the same to a human, but the program runs faster.

Discussion No comments have been posted yet, so there is no discussion to summarize.

#linebuffering #terminal #stdio #performance #nagleAlgorithm #C