我面临着逐行读取/写入文件(在演出中)的挑战。
阅读许多论坛条目和站点(包括一堆 SO),mmap 被建议作为读取/写入文件的最快选项。但是,当我使用 readline 和 mmap 技术实现代码时,mmap 是两者中较慢的一个。对于阅读和写作来说都是如此。我一直在使用约 600 MB 大的文件进行测试。
我的实现逐行解析,然后标记该行。我将仅介绍文件输入。
这里是getline执行:
void two(char* path) {
std::ios::sync_with_stdio(false);
ifstream pFile(path);
string mystring;
if (pFile.is_open()) {
while (getline(pFile,mystring)) {
// c style tokenizing
}
}
else perror("error opening file");
pFile.close();
}
这是mmap:
void four(char* path) {
int fd;
char *map;
char *FILEPATH = path;
unsigned long FILESIZE;
// find file size
FILE* fp = fopen(FILEPATH, "r");
fseek(fp, 0, SEEK_END);
FILESIZE = ftell(fp);
fseek(fp, 0, SEEK_SET);
fclose(fp);
fd = open(FILEPATH, O_RDONLY);
map = (char *) mmap(0, FILESIZE, PROT_READ, MAP_SHARED, fd, 0);
/* Read the file char-by-char from the mmap
*/
char c;
stringstream ss;
for (long i = 0; i <= FILESIZE; ++i) {
c = map[i];
if (c != '\n') {
ss << c;
}
else {
// c style tokenizing
ss.str("");
}
}
if (munmap(map, FILESIZE) == -1) perror("Error un-mmapping the file");
close(fd);
}
为了简洁起见,我省略了很多错误检查。
我的 mmap 实现是否不正确,从而影响性能?也许 mmap 不适合我的应用程序?
感谢您的任何意见或帮助!