返回信息流对于一些需要需要高磁盘访问的应用。尽量减少磁盘io操作时提高效率的一种方式。
下面提供两种缓存,批量写文件的方法。
方法一:预先分配内存,先把要写入到磁盘上的内容写入内存,到达一定容量,批量写如磁盘
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#define MAXLEN 16*1024*1024
int main()
{
char * fp = (char*)malloc(MAXLEN+1024);
clock_t begin = clock();
if(fp == NULL)
{
printf("malloc error\n");
exit(0);
}
memset(fp, 0, MAXLEN);
unsigned int pos = 0;
while(1)
{
pos += sprintf(fp+pos, "this test mem file\n");
if(pos >= MAXLEN)
break;
}
int fd = open("memfile.txt", O_WRONLY| O_TRUNC|O_CREAT, 0666);
if(fd == -1)
{
printf("open file error\n");
exit(0);
}
int wlen = write(fd, fp, pos);
if(wlen != pos)
{
printf("write %d bytes once\n", wlen);
}
printf("write %d bytes: total : %d bytes\n", wlen, pos);
close(fd);
free(fp);
clock_t end = clock();
printf("spend time %d\n", end-begin);
return 0;
}
方法二:利用mmap,进行文件映射。
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define MAXLEN 16*1024*1024
int main()
{
int fd = open("map.txt", O_RDWR| O_TRUNC|O_CREAT, 0777);
ftruncate(fd , MAXLEN);
char* mp = (char*)mmap(0, MAXLEN, PROT_READ|PROT_WRITE, MAP_SHARED , fd , 0);
close(fd);
if(mp == (char*)-1)
{
printf("map null %s\n", strerror(errno));
exit(0);
}
unsigned int pos = 0;
clock_t begin = clock();
while(1)
{
pos += sprintf(mp+pos, "this test mem file\n");
if(pos+1024 >= MAXLEN)
break;
}
munmap(mp, MAXLEN);
clock_t end = clock();
printf("spend %d \n", end-begin);
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #10197同步于 2008/7/31
CPP机器人发帖
两个批量写文件的方法
redfox
2008/7/31镜像同步0 回复
订阅后,新回复会通过你的通知中心匿名送达。
0 条回复
暂无回复 · 你可以订阅本帖等待新回复。