speed comparison between fgetc/fputc and fread/fwrite in C

后端 未结 4 1482
借酒劲吻你
借酒劲吻你 2020-12-17 01:08

So(just for fun), i was just trying to write a C code to copy a file. I read around and it seems that all the functions to read from a stream call fgetc() (I ho

4条回答
  •  有刺的猬
    2020-12-17 01:21

    Like sehe says its partly because buffering, but there is more to it and I'll explain why is that and at the same why fgetc() will give more latency.

    fgetc() is called for every byte that is read from from file.

    fread() is called for every n bytes of the local buffer for file data.

    So for a 10MiB file:

    fgetc() is called: 10 485 760 times

    While fread with a 1KiB buffer the function called 10 240 times.

    Lets say for simplicity that every function call takes 1ms: fgetc would take 10 485 760 ms = 10485.76 seconds ~ 2,9127 hours fread would take 10 240 ms = 10.24 seconds

    On top of that the OS does reading and writing on usually the same device, I suppose your example does it on the same hard disk. The OS when reading your source file, move the hard disk heads over the spinning disk platters seeking the file and then reads 1 byte, put it on memory, then move again the reading/writing head over the hard disk spinning platters looking on the place that the OS and the hard disk controller agreed to locate the destination file and then writes 1 byte from memory. For the above example this happens over 10 million times for each file: totaling over 20 million times, using the buffered version this happens just a grand total of over 20 000 times.

    Besides that the OS when reading the disk puts in memory a few more KiB of hard disk data for performance purposes, an this can speed up the program even when using the less efficient fgetc because the program read from the OS memory instead of reading directly from the hard disk. This is to what sehe's response refers.

    Depending on your machine configuration/load/OS/etc your results from reading and writing can vary a lot, hence his recommendation to empty the disk caches to grasp better more meaningful results.

    When source and destination files are on different hdd things are a lot faster. With SDDs I'm not really sure if reading/writing are absolutely exclusive of each other.

    Summary: Every call to a function has certain overhead, reading from a HDD has other overheads and caches/buffers help to get things faster.

    Other info

    http://en.wikipedia.org/wiki/Disk_read-and-write_head

    http://en.wikipedia.org/wiki/Hard_disk#Components

提交回复
热议问题