IO效率测试的报告
其中writefile.c是要写入的文件,hello.c是要读入的文件,此文件的大小为十几兆(一般要比较大结果才可信);
(1)无缓冲IO
#include "ourh.h"
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/times.h>
unsigned long cifang(int n)
{
unsigned long temp=1;
int i;
for(i=0;i<n;i++)
{
temp=temp*2;
}
return temp;
}
void print_times(int bufsize,clock_t real,struct tms* start,struct tms* end)
{
long clktck=0;
clktck=sysconf(_SC_CLK_TCK);
printf("%d %f %f %f/n",bufsize,(end->tms_utime-start->tms_utime)/(double)clktck,(end->tms_stime-start->tms_stime)/(double)clktck,real/(double)clktck);
}
int main()
{
int n;
unsigned long BUFFERSIZE=1;
struct tms tms_start,tms_end;
time_t c_start,c_end;
int i=0;
while(i<23)
{
BUFFERSIZE=cifang(i);
char buf[BUFFERSIZE];
int outfile=open("writefile.c",O_RDWR|O_TRUNC|O_CREAT,0644);
int infile=open("hello.c",O_RDONLY);
c_start = times(&tms_start);
while((n=read(infile,buf,BUFFERSIZE))>0)
{
if(write(outfile,buf,n)!=n)
err_sys("write error");
}
if(n<0)
{
err_sys("read error");
}
c_end = times(&tms_end);
printf("buf user sys real/n");
print_times(BUFFERSIZE,c_end-c_start,&tms_start,&tms_end);
close(outfile);
close(infile);
i++;
}
return 0;
}
运行结果:
(2)标准IO
#include "ourh.h"
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/times.h>
void print_times(int bufsize,clock_t real,struct tms* start,struct tms* end)
{
long clktck=0;
clktck=sysconf(_SC_CLK_TCK);
printf("%d %f %f %f/n",bufsize,(end->tms_utime-start->tms_utime)/(double)clktck,(end->tms_stime-start->tms_stime)/(double)clktck,real/(double)clktck);
}
int main()
{
int n;
unsigned long BUFFERSIZE=1024;
struct tms tms_start,tms_end;
time_t c_start,c_end;
char buf[BUFFERSIZE];
FILE* outfile=fopen("writefile.c","w+");
FILE* infile=fopen("hello.c","r+");
c_start = times(&tms_start);
while(fgets(buf,BUFFERSIZE,infile)!=NULL)
{
if(fputs(buf,outfile)==EOF)
err_sys("write error");
}
if(ferror(infile))
{
err_sys("read error");
}
c_end = times(&tms_end);
printf("buf user sys real/n");
print_times(BUFFERSIZE,c_end-c_start,&tms_start,&tms_end);
fclose(outfile);
fclose(infile);
return 0;
}
运行结果:
从结果可以看出:
用无缓冲IO读写函数操作时,当缓冲区大小设置为131072时效率最高,时间分别为
0.000000 0.020000 0.012000