问题描述
提供相同的节目其内容随机生成的输入文件,并回读给输出相同的字符串后。唯一的区别是,在一边,我提供的读写从Linux系统调用的方法,并在另一边我用FREAD / FWRITE。
计时我的应用程序,在尺寸的为10Mb输入和呼应它到/ dev / null的,并确保该文件没有缓存,我发现,libc中的FWRITE使用非常小的缓冲区(当快被大规模的情况下,1个字节)。
下面是我的时间输出,使用FWRITE:
真正0m0.948s
用户0m0.780s
SYS 0m0.012s
和使用系统调用写:
真正0m8.607s
用户0m0.972s
SYS 0m7.624s
这是我能想到的唯一的可能就是内部的libc已经是我的缓冲输入。可惜我找不到网络上的很多信息,所以也许这里的高手们可以帮助我。
fwrite
works on streams, which are buffered. Therefore many small buffers will be faster because it won't run a costly system call until the buffer fills up (or you flush it or close the stream). On the other hand, small buffers being sent to write
will run a costly system call for each buffer - that's where you're losing the speed. With a 1024 byte stream buffer, and writing 1 byte buffers, you're looking at 1024 write
calls for each kilobyte, rather than 1024 fwrite
calls turning into one write
- see the difference?
For big buffers the difference will be small, because there will be less buffering, and therefore a more consistent number of system calls between fwrite
and write
.
In other words, fwrite(3)
is just a library routine that collects up output into chunks, and then calls write(2)
. Now, write(2)
, is a system call which traps into the kernel. That's where the I/O actually happens. There is some overhead for simply calling into the kernel, and then there is the time it takes to actually write something. If you use large buffers, you will find that write(2)
is faster because it eventually has to be called anyway, and if you are writing one or more times per fwrite then the fwrite buffering overhead is just that: more overhead.
If you want to read more about it, you can have a look at this document, which explains standard I/O streams.
这篇关于为什么FWRITE libc的功能比系统调用write函数更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!