首页 > 解决方案 > synchronized_pool_resource 实际是如何工作的?

问题描述

我正在研究 C++17 中的多态内存分配。我修改了一个使用 monotonic_buffer_resource 进行向量分配的示例,以使用 synchronized_pool_resource。我发现了一个奇怪的行为。具体来说,有很多内存分配,仅用于向量中的两个加法。我没有运行基准测试,但我认为这是对性能的巨大损失

该程序使用 O2 g++ -std=c++17 -O2 -Wall -pedantic 编译

下面是代码

class debug_resource : public std::pmr::memory_resource {

public:
    explicit debug_resource(std::string name,
        std::pmr::memory_resource* up = std::pmr::get_default_resource())
        : _name{ std::move(name) }, _upstream{ up }
    { }

    void* do_allocate(size_t bytes, size_t alignment) override {
        std::cout << _name << " do_allocate(): " << bytes << '\n';
        void* ret = _upstream->allocate(bytes, alignment);
        return ret;
    }
    void do_deallocate(void* ptr, size_t bytes, size_t alignment) override {
        std::cout << _name << " do_deallocate(): " << bytes << '\n';
        _upstream->deallocate(ptr, bytes, alignment);
    }
    bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
        return this == &other;
    }

private:
    std::string _name;
    std::pmr::memory_resource* _upstream;
};
int main()
{
  
    debug_resource default_dbg{ "default" };
    std::pmr::synchronized_pool_resource pool(&default_dbg);
  //  debug_resource dbg{ "pool", &pool };
    std::pmr::vector<std::string> strings{ &pool };

   strings.emplace_back("Hello Short String");
   strings.emplace_back("Hello Short String 2");
}

控制台输出如下

默认 do_allocate(): 32
默认 do_allocate(): 528
默认 do_allocate(): 32
默认 do_allocate(): 528
默认 do_allocate(): 1000
默认 do_allocate(): 192
默认 do_allocate(): 968
默认 do_allocate(): 192

默认do_deallocate():528
默认do_deallocate():32
默认do_deallocate():1000
默认do_deallocate():192
默认do_deallocate():968
默认do_deallocate():192
默认do_deallocate():528
默认do_deallocate():32

标签: c++c++17allocatorc++pmr

解决方案


答案在函数说明中:https ://en.cppreference.com/w/cpp/memory/synchronized_pool_resource

它由一组池组成,这些池为不同块大小的请求提供服务。每个池管理一组块,然后将这些块分成大小一致的块。

对 do_allocate 的调用被分派到为满足请求大小的最小块提供服务的池中。

耗尽池中的内存会导致该池的下一个分配请求从上游分配器分配额外的内存块以补充池。获得的块大小呈几何级数增加

最大块大小和最大块大小可以通过将 std::pmr::pool_options 结构传递给其构造函数来调整。

所以池实际上是内存块的集合。并且在必要时增加这个集合。因此多次分配。

要减少分配数量,您可以尝试使用std::pmr::pool_options


推荐阅读