5

我使用下面的代码来测量读取内存映射文件的大型顺序读取与仅调用之间的性能差异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来更改测试。)

令我惊讶的ReadFile是,速度慢了约 20%!为什么?

4

1 回答 1

7

FILE_FLAG_NO_BUFFERING跛子ReadFile。内存映射文件可以自由地使用它想要的任何预读算法,并且您禁止ReadFile这样做。您仅在ReadFile版本中关闭了缓存。没有文件缓存,内存映射文件就无法工作。

于 2011-03-10T13:15:56.047 回答