我面临逐行读取/写入文件(在 Gigs 中)的挑战。
阅读许多论坛条目和站点(包括一堆 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 不适合我的应用程序?
Thanks for any comments or help!