直接IO和标准文件IO对比
具体代码
直接IO的代码
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#define BUF_SIZE 512
int debug = 0;
int main(int argc, char *argv[])
{
char *buf = NULL ;
const char *filename = "./write.txt";
int fd = -1;
time_t start, cur;
int rlen = 0,ret = 0;
static int read_total = 0;
ret = posix_memalign((void **)&buf, 512, BUF_SIZE);
if (ret) fprintf(stderr, "posix_memalign failed. reason: %s\n", strerror(errno));
start = time(NULL);
do{
read_total++;
fd = open(filename, O_RDWR | O_DIRECT);
if (fd < 0)
{
fprintf(stderr, "fopen %s failed, reason: %s. \nexit. \n", filename, strerror(errno));
return -1;
}
do{
if (rlen = read(fd, buf, BUF_SIZE) < 0)
{
fprintf(stderr, "read from %s failed, reason: %s. \nexit. \n", filename, strerror(errno));
}
if (debug) printf("read: %d\n", rlen);
}while(rlen > 0);
printf(" finished.\n");
close(fd);
cur = time(NULL);
}while((cur-start) < 20);
printf("total num: %d\n", read_total);
return 0;
}
具体操作
标准IO的代码
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#define BUF_SIZE 512
int debug = 0;
int main(int argc, char *argv[])
{
char *buf = NULL ;
const char *filename = "./write.txt";
int fd = -1;
time_t start, cur;
int rlen = 0,ret = 0;
static int read_total = 0;
ret = posix_memalign((void **)&buf, 512, BUF_SIZE);
if (ret) fprintf(stderr, "posix_memalign failed. reason: %s\n", strerror(errno));
start = time(NULL);
do{
read_total++;
//fd = open(filename, O_RDWR | O_DIRECT);
fd = open(filename, O_RDWR);
if (fd < 0)
{
fprintf(stderr, "fopen %s failed, reason: %s. \nexit. \n", filename, strerror(errno));
return -1;
}
do{
if (rlen = read(fd, buf, BUF_SIZE) < 0)
{
fprintf(stderr, "read from %s failed, reason: %s. \nexit. \n", filename, strerror(errno));
}
if (debug) printf("read: %d\n", rlen);
}while(rlen > 0);
//printf(" finished.\n");
close(fd);
cur = time(NULL);
}while((cur-start) < 20);
printf("total num: %d\n", read_total);
return 0;
}
运行结果
没有对比就没有伤害
结语:
时间: 2020-08-15