gpt4 book ai didi

c++ - synchronized_pool_resource 实际是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 10:10:39 26 4
gpt4 key购买 nike

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

最佳答案

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

It consists of a collection of pools that serves request for differentblock sizes. Each pool manages a collection of chunks that are thendivided into blocks of uniform size.

Calls to do_allocate are dispatched to the pool serving the smallestblocks accommodating the requested size.

Exhausting memory in the pool causes the next allocation request forthat pool to allocate an additional chunk of memory from the upstreamallocator to replenish the pool. The chunk size obtained increasesgeometrically.

The largest block size and maximum chunk size may be tuned by passinga std::pmr::pool_options struct to its constructor.


所以池实际上是内存块的集合。并且在必要时增加这个集合。因此多次分配。
要减少分配的数量,您可以尝试使用 std::pmr::pool_options .

关于c++ - synchronized_pool_resource 实际是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63683240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com