标准IO和系统IO写入速度比较
众所周知,标准IO的速度要比系统IO快。
那为什么系统调用要比标准C库调用慢呢?
测试:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void stdIOwrite(void){
FILE* file = fopen("writetst.dat","w");
for(int i=0;i<1000000;i++){
fwrite(&i,sizeof(int),1,file);
}
fclose(file);
}
void sysIOwrite(void){
int fd = open("writetst.dat",O_TRUNC|O_WRONLY);
for(int i=0;i<1000000;i++){
write(fd,&i,sizeof(int));
}
close(fd);
}
int main(){
//sysIOwrite();
stdIOwrite();
}
系统IO写入100W个整数所用时间:
real 0m47.595s
user 0m0.813s
sys 0m45.859s
标准IO写入100w个整数所用时间:
real 0m0.096s
user 0m0.031s
sys 0m0.063s
解答
-
因为标准IO使用了缓冲技术,当数据写入时,并没有交给内核,而是先放在缓冲区中,当缓冲区慢时,会一次性把缓冲区中的数据交给内核,写入文件。
-
调用系统IO会频繁进出系统内核,浪费大量时间在内核态和用户态的切换。
为系统IO添加简易缓冲区
void sysIOwrite(void){
int fd = open("writetst.dat",O_TRUNC|O_WRONLY);
int arr[500];
for(int i=0;i<1000000;i++){
arr[(i+1)%500] = i;
if((i+1)%500 == 0){
write(fd,arr,sizeof(int)*500);
}
}
close(fd);
}
运行效果:
real 0m0.153s
user 0m0.016s
sys 0m0.109s
变快了不少