C语言涉及文件的函数执行慢,c语言分别用库函数和系统函数来进行文件操作效率对比...

本文探讨了使用C/C++编程时,通过库函数fopen/fputc和系统调用open/read/write进行文件操作的效率差异。库函数方法速度较快,而系统调用涉及更多内核交互,导致速度下降。作者通过strace分析揭示了原因和内核缓存的影响。
摘要由CSDN通过智能技术生成

使用库函数来进行文件读取

#include

#include

int main(void)

{

FILE *fp, *fp_out;

int n;

fp = fopen("dict.txt", "r");

if (fp==NULL){

perror(fopen error);

exit(1);

}

fp_out = fopen("dict.cp", "w");

if (fp_out ==NULL){

perror("fopen error");

exit(1);

}

while((n=fgetc(fp))!=EOF){

fputc(n, fp_out);

}

fclose(fp);

fclose(fp_out);

}

# 编译好之后直接运行速度非常快

使用系统调用

#include

#include

#include

#include

#include

#include

#define N 1

int main(int agrc, char *argv)

{

int fd, fd_out;

int n;

char buf[N];

fd = open("dict.txt", O_RDONLY);

if (fd<0){

perror("open dict.txt error");

exit(1);

}

fd_out = open("dict.cp", O_WRONLY|O_CREAT|O_TRUNC, 0644);

if (fd_out < 0 ){

perror("open dict.cp error");

exit(1);

}

while((n=read(fd, buf, N))){

if (n<0){

perror("read error");

exit(1);

}

write(fd_out, buf, n);

}

close(fd);

close(fd_out);

return 0;

}

# 很明显速度要比库函数调用要慢的多

为什么系统调用要比库函数效率要低

使用strace可以详细看到运行的调用结果,发现调用的次数要少的多

内核缓存有4096字节的大小

用户空间进入内核空间要耗时比较多,但是比内核到磁盘要快

20200318181410080645.png

fputc 中有一个字节的缓存区,达到4096之后在会进入到内核空间中

read write是属于无用户级缓存

原文:https://www.cnblogs.com/fandx/p/12518274.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值