【问题标题】:mmap() and actual physical allocation of the pages under Linuxmmap()和Linux下页面的实际物理分配
【发布时间】:2021-12-20 08:20:39
【问题描述】:

当我使用 MEM_RESERVE 执行 VirtualAlloc 时 | Windows 下的 MEM_COMMIT 虚拟分配的页面实际上并没有立即获得分配的物理页面,而是首先从页面文件中减去页面,然后在第一次访问页面时按需映射(我已经测量了延迟此映射的 >= 1.000 个时钟周期)。

但是 Linux 是什么?当我过度使用时,对我来说很明显物理页面会立即分配。但是当我关闭过度使用并拥有 mmap() 时会发生什么?如果物理分配立即失败,系统是否会从页面文件/分区中减去必要的空间以获得支持? IE。然后页面是否像在 Windows 下那样动态分配?

【问题讨论】:

    标签: linux-kernel mmap


    【解决方案1】:

    好的,所以我写了一个小程序来扫描新分配的 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。

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 2015-05-29
      相关资源
      最近更新 更多