C++ - 我读取了整个文件(_这是一个由 2 个空格分隔的单词列表_),如何快速分别获取单词?

标签 c++ performance file buffer multimap

我已经阅读了一个大约 120k 字的文件,所以我尝试快速阅读。 看过:

int x = setvbuf(fp, (char *)NULL, _IOFBF, BSZ);
assert( x == 0 && fp != NULL );

选项,但它需要一秒钟以上(1 mb 文件) 所以现在我尝试了这个方法:

fopen_s (&pFile,DICT,"rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);

我如何从这里继续? 缓冲区包含一个单词列表,我想尽快一个一个地获取它们 因为我正在用这些词构建多重映射。

谢谢!

最佳答案

您的代码本质上是在实现 mmap()mmap() 的美妙之处在于它会在需要时将实际页面加载到内存中。如果您的应用按顺序读取它们的速度非常快,操作系统将尽可能快地映射页面。

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define handle_error(msg) \
    { perror(msg); exit(EXIT_FAILURE); }

int
main(void)
{
    int fd = open("english-words.10", O_RDONLY);
    if (fd == -1)
        handle_error("open");

    struct stat sb;
    if (fstat(fd, &sb) == -1)
        handle_error("fstat");
    size_t lSize = sb.st_size;

    char* buffer = mmap(NULL, lSize, PROT_READ, MAP_PRIVATE, fd, 0);
    if (buffer == MAP_FAILED)
        handle_error("mmap");

    // insert your mapping to a map here

    munmap(buffer, lSize);

    return 0;
}

请注意,我还使用了 fstat() 而不是您的 fseek/ftell

关于C++ - 我读取了整个文件(_这是一个由 2 个空格分隔的单词列表_),如何快速分别获取单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574977/

相关文章:

c++ - 如何获取适用于 Visual Studio 的 Boost 库二进制文件?

c++ - Visual C++ 内存块填充

c# - Mono C# WinForms -> 在 Mac OSX 上运行时出现严重的性能问题

c++ - C++目录中的文件

c++ - 如何释放 vector 中的对象指针?

c++ - 静态变量会阻碍数据缓存吗?

c++ - 循环展开有利的条件以及返回率下降的点?

c - 如何从 visual studio 2010 调用批处理文件

cocoa - 在 Cocoa 中加载 OpenAL 的 .wav 文件

c++ - vector 、指针、类和 EoF 循环 (C++)