我正在尝试从内存映射文件中读取,但访问该文件需要很长时间。我正在将整个文件映射到我的程序,并且初始访问速度很快,但随后它开始急剧变慢
文件约为 47gb,我有 16gb 的 RAM。我正在使用 Visual Studios 作为我的 IDE 在 Windows 7 上运行一个 64 位应用程序。下面是我的代码片段
hFile = CreateFile( "Valid Path to file", // name of the write
GENERIC_READ , // open for reading
0, // do not share
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
cout << "Unable to open vals" << endl;
exit(1);
}
hMapFile = CreateFileMapping(
hFile,
NULL, // default security
PAGE_READONLY, // read/write access
0, // maximum object size (high-order DWORD)
0, // maximum object size (low-order DWORD)
NULL); // name of mapping object
if (hMapFile == NULL)
{
cout<< "Error code " << GetLastError() << endl;
exit(1);
}
data = (float*) MapViewOfFile(
hMapFile,
FILE_MAP_READ,
0,
0,
0);
if (data == NULL)
{
cout << "Error code " << GetLastError() << endl;
CloseHandle(hFile);
exit(1);
}
这仅仅是因为文件太大以至于不断交换文件 block 需要很长时间,还是我需要一些其他参数来加快访问速度?
编辑: 我尝试使用只读而不是使用上面看到的读、写、执行,但速度仍然很慢。我了解内存映射和交换交换空间的概念,但我认为我可能做错了什么阻碍了速度
最佳答案
这是因为分页。发生的情况是您的 RAM 只能容纳 16GB 的文件(实际上它更少,因为您的计算机上运行了其他程序,但为了简单起见,我们只使用它)。
因此,如果您在程序中访问不在 RAM 中的文件部分(比方说,文件的一部分在 20GB 段中),您的 RAM 需要与磁盘通信并传输一个全新的段文件到 RAM。这需要很多时间。
关于c++ - 内存映射文件很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410840/