问题描述
我使用下面的代码来衡量读取内存映射文件的大的、顺序的读取与仅调用ReadFile
相比的性能差异:
I used the code below to measure the performance difference between reading large, sequential reads of a memory-mapped file, as compared to just calling ReadFile
:
HANDLE hFile = CreateFile(_T("D:\\LARGE_ENOUGH_FILE"),
FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING, NULL);
__try
{
const size_t TO_READ = 32 * 1024 * 1024;
char sum = 0;
#if TEST_READ_FILE
DWORD start = GetTickCount();
char* p = (char*)malloc(TO_READ);
DWORD nw;
ReadFile(hFile, p, TO_READ, &nw, NULL);
#else
HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY,
0, 0, NULL);
const char* const p = (const char*)MapViewOfFile(hMapping,
FILE_MAP_READ, 0, 0, 0);
DWORD start = GetTickCount();
#endif
for (size_t i = 0; i < TO_READ; i++)
{
sum += p[i]; // Do something kind of trivial...
}
DWORD end = GetTickCount();
_tprintf(_T("Elapsed: %u"), end - start);
}
__finally { CloseHandle(hFile); }
(我只是改变了TEST_READ_FILE
的值来改变测试.)
(I just changed the value of TEST_READ_FILE
to change the test.)
令我惊讶的是,ReadFile
慢约 20%!为什么?
To my surprise, ReadFile
was slower by ~20%! Why?
推荐答案
FILE_FLAG_NO_BUFFERING
削弱了 ReadFile
.内存映射文件可以随意使用它想要的任何预读算法,并且您已经禁止 ReadFile
这样做.您仅在 ReadFile
版本中关闭了缓存.没有文件缓存,内存映射文件就无法工作.
FILE_FLAG_NO_BUFFERING
cripples ReadFile
. The memory-mapped file is free to use whatever read-ahead algorithm it wants, and you've forbidden ReadFile
to do the same. You've turned off caching only in the ReadFile
version. Memory-mapped files can't work without file cache.
这篇关于内存映射文件在大量顺序读取时速度更快?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!