Fwrite () vs write () in the presence of disk caching

Idea / fact # 1 I have read a few posts about how streams are buffered, so fwrite () is usually a buffered stream. On the other hand, write () will not be buffered. Why is fwrite libc faster than writing to syscall?

Idea / fact # 2 I also studied an article on disk caching and how Linux uses it to improve disk performance. http://www.linuxatemyram.com/play.html

So with disk buffering in place, which Linux shouldn't do by default fwrite (), and write () will show the same performance? What fwrite () does is "buffering over an already buffered disk"! which shouldn't give a huge boost. What am I missing here?

+3


source to share


1 answer


fwrite

disk buffering and caching operate at two different levels.

fwrite

works at the program level: it buffers numerous small records and concatenates them together to make one system call, rather than an individual system call for each small record. This saves you repeated overhead when switching from user mode to kernel mode and back.



Disk caching works at the kernel level, by concatenating disk records, which allows them to linger. Hard drives can be slow, so if you have to wait for all the data to be consumed by the drive driver, your program will be delayed. By using a cache, which is generally much faster than disk, you can complete the write much faster and return to your program. While the program continues to run, the cache will be slowly flushed to disk unless the program has to wait for it.

+6


source







All Articles