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是屬於無用戶級緩存
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章