在有时候,项目的数据量特别大,而且源源不断的到来,这个时候,利用传统的IO文件流写文件势必效率很低跟不上节奏。我这里的场景是:生存者A,消费者B,消息队列C。A高速生产数据并缓存至C,B不停的从C取数据,并写入本地文件。不妨采用内存映射方式来写文件,达到高效,至于相比于传统IO能够快多少,可以作个比较,我这边两者差距特别大。关于mmap的相关API,请参阅网上其他地方,这里不再敖述。直接贴例子代码。
<span style="font-family:Courier New;font-size:14px;">#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include <string>
#include <iostream>
using namespace std;
/* 获取要写入文件的长度 */
int getFileSize(const string &filename)
{
int size = 0;
FILE *fp = NULL;
fp=fopen(filename.c_str(),"r");
if( NULL == fp)
{
return size;
}
fseek(fp,0L,SEEK_END);
size = ftell(fp);
fclose(fp);
return size;
}
void mmapSaveDataIntoFiles(const string &filename

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



