UC编程:通过fwrite()和write()比较标准库函数和系统调用的速度

时间:2023-03-09 00:49:07
UC编程:通过fwrite()和write()比较标准库函数和系统调用的速度

fwrte是C标准库中提供的函数,是对write函数的扩展与封装,write则是Unix系统提供的函数。按照常理来讲,系统调用肯定比使用库快的多,但是事实正好相反 Why?原因就在于缓冲的问题,fwite会在内存中开辟缓冲区,来避免频繁的I/O,所以速度比系统调用要快(更多比较“open/read/write和fopen/fread/fwrite的区别”)

为了直观的比较一下fwrite和write的速度。我们来做一个简单的测试:

fwrite.c

[c]
#include <stdio.h>

int main(void)
{
FILE *stream;
int i;
char str[] = "qwertyuiop\n";
if ((stream = fopen("fwrite.txt", "w")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
for(i=0; i<100000; i++)
{
fwrite(str, sizeof(str), 1, stream);
}
fclose(stream); /*关闭文件*/
return 0;
}
[/c]

运行时间:

[code]
real 0m0.009s
user 0m0.003s
sys 0m0.005s
[/code]

write.c

[c]
#include <stdio.h>
#include <fcntl.h>

int main(void)
{
int fd;
int i;
char str[] = "qwertyuiop\n";
if ((fd = open("write.txt", O_RDWR|O_CREAT|O_TRUNC, 00664)) < 0)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
for(i=0; i<100000; i++)
{
write(fd, str, sizeof(str));
}
close(fd); /*关闭文件*/
return 0;
}
[/c]

运行时间:

[code]
real 0m0.189s
user 0m0.008s
sys 0m0.181s
[/code]

果然,从程序运行时间上看,使用标准库函数速度比直接系统调用快了很多 从程序的可移植性角度来讲,使用标准库函数也是一个好的习惯 而系统调用则是用在和系统关联度很高的地方