David
David

Reputation: 4818

fwrite() vs write() in presence of disc caching

Idea/Fact #1 I was reading few post about how the streams are buffered so fwrite() is usually buffered stream. On the other hand write() will not be buffered. Why the fwrite libc function is faster than the syscall write function?

Idea/Fact #2 I was also looking into the article about disc caching and how Linux uses it heavily to improve the disc performance substantially. http://www.linuxatemyram.com/play.html

So in the presence of disc buffering which Linux do by default shouldn't fwrite() and write() will render same performance? What fwrite() is doing is a "buffering over already buffered disc"! which should not give huge boost. What am i missing here?

Upvotes: 3

Views: 1724

Answers (1)

MicroVirus
MicroVirus

Reputation: 5487

fwrite buffering and disk caching work on two very different levels.

fwrite works on the program level: it buffers numerous small writes and pools them together to make one system call, rather than an individual system call for each small write. This saves you the repeated overhead of switching from user mode to kernel mode and back.

Disk caching works on the kernel level, by pooling disk writes, allowing them to be delayed. Hard disks can be slow, so if you'd have to wait for all the data to be consumed by the disk driver, then your program will be delayed. By utilising cache, which is generally much faster than the drive, you can complete the write much faster and return to the program. While the program continues running, the cache will slowly be emptied onto the disk, without the program having to wait for it.

Upvotes: 6

Related Questions