好的,所以我写了一个小程序来扫描新分配的 mmap() 页面
#if defined(_MSC_VER)
#include <Windows.h>
#elif defined(__unix__)
#include <sys/mman.h>
#endif
#include <iostream>
#include <chrono>
#include <atomic>
using namespace std;
using namespace chrono;
int main()
{
static size_t const SIZE = (size_t)8 << 30, N_PAGES = SIZE >> 12;
#if defined(_MSC_VER)
void *p = VirtualAlloc( nullptr, SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE );
#elif defined(__unix__)
void *p = mmap( nullptr, SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0 );
#endif
if( !p )
return EXIT_FAILURE;
auto scan = [&]()
{
auto start = high_resolution_clock::now();
for( atomic<char> *pc = (atomic<char> *)p, *pcEnd = pc + SIZE; pc < pcEnd; pc->store( 0, memory_order_relaxed ), pc += 0x1000 );
return (double)(int64_t)duration_cast<nanoseconds>( high_resolution_clock::now() - start ).count() / N_PAGES;
};
cout << scan() << endl;
cout << scan() << endl;
}
在我的 Linux Ryzen 7 1800X PC 上,第一次 scan() 每页大约 1.800ns,后者大约为 60ns。而且我的 Ubuntu 计算机启用了过度使用,因此这肯定也适用于非过度使用。所以 Linux 在这里具有与 Windows 相同的行为。我的带有 Ryzen Threadripper 3990X 的 Windows-PC 在这里明显更快;第一次 scan() 每页大约 700ns。