Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I/O to Screen/Standard Output

Tags:

c

io

I noticed that in any program that I write, the time taken to execute is significantly slower if I do a lot of printing to the monitor (i.e. printf or fprintf (stderr, "...")).

I figured that writing to the disk will be slow, because of the physical limitations of the disk. I'm not sure why printing to the screen should slow the program down significantly.

like image 985
Kitchi Avatar asked Feb 27 '26 02:02

Kitchi


1 Answers

Writing to a terminal is not exactly fast and is not designed to be fast since usually the only stuff that goes to stdout are pieces of information for the user who is bound by how fast he or she can read stuff.

When you write to the terminal on eg. linux, the following stuff happens (maybe). The kernel is being called between each two consecutive steps:

  1. Your program issues a write system call to write data.
  2. The kernel resumes your terminal emulator and yields the data written to the terminal device
  3. The terminal emulator renders its frame's new state and sends this to the X server
  4. The X server manipulates memory mapped display regions
  5. The kernel tells your graphics card to swap buffers

And those are a lot of steps... Since terminal output is usually only line-buffered, this occurs pretty often.

like image 127
fuz Avatar answered Feb 28 '26 19:02

fuz