首页 > 编程语言 > 详细

c语言分别用库函数和系统函数来进行文件操作效率对比

时间:2020-03-18 18:14:09      阅读:76      评论:0      收藏:0      [点我收藏+]

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

#include <stdio.h>
#include <stdlib.h>

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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#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字节的大小
  • 用户空间进入内核空间要耗时比较多,但是比内核到磁盘要快

技术分享图片

  • fputc 中有一个字节的缓存区,达到4096之后在会进入到内核空间中
  • read write是属于无用户级缓存

c语言分别用库函数和系统函数来进行文件操作效率对比

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!