【问题标题】:How the synchronized_pool_resource actually works?synchronized_pool_resource 实际是如何工作的?
【发布时间】:2020-09-01 07:32:02
【问题描述】:

我正在研究 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

【问题讨论】:

  • 要查看字符串的额外分配,您应该使用 std::pmr::string 作为元素的类型,而不是 std::string

标签: c++ c++17 allocator c++pmr


【解决方案1】:

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

它由一个池集合组成,为不同的请求提供服务 块大小。 每个池管理一组块,然后 分成大小均匀的块。

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

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

最大块大小和最大块大小可以通过传递来调整 一个 std::pmr::pool_options 结构到它的构造函数。

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

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

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2011-09-27
    • 2021-12-16
    • 2013-03-14
    • 2021-03-23
    • 2011-02-11
    • 2012-04-06
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多