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


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

    #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是属于无用户级缓存
  • 相关阅读:
    Linux 工具命令
    Js的一些工具方法
    使用curl测试网络通信
    python 创建XML
    Nginx 使用Lua脚本
    lua 安装cjson
    3对象和类_动手动脑
    10.5
    10.4动手动脑
    10.2
  • 原文地址:https://www.cnblogs.com/fandx/p/12518274.html
Copyright © 2020-2023  润新知