【发布时间】:2011-09-29 14:35:40
【问题描述】:
我正在使用一个内存池类,它重用分配的内存地址和一个自定义分配器,它包装 那堂课。下面的代码 sn -p 让你对接口有一个基本的了解。
template<class alloc>
class memory_pool
: boost::noncopyable,
public allocator_traits<void>
{
public:
memory_pool(typename alloc::size_type alloc_size);
memory_pool(typename alloc::size_type alloc_size, alloc const&);
template<typename U> memory_pool(typename alloc::size_type alloc_size,
typename alloc::rebind<U>::other const&);
virtual ~memory_pool();
pointer allocate (); /*throw(std::bad_alloc)*/
void collect ();
void deallocate(pointer) throw(); /*noexcept*/
};
pointer allocate()
{/*
Checks if a suitable chunk of memory is available in a internal linked list.
If true, then the chunk is returned and the next chunk moves up.
Otherwise, new memory is allocated by the underlying allocator.
*/}
void deallocate(pointer)
{/*
Interprets the passed pointer as a chunk of memory and stores it in a linked list.
Please note that memory isn't actually deallocated.
*/}
void collect()
{/*
Effectively deallocates the cunks in the linked list.
This will be called at least once during destruction.
*/}
当然,这样的需求是有限的。但是,它在您需要的情况下非常有用 到: - 为以非常幼稚的方式使用分配器的类指定分配器类型(例如避免 分配更大的部分,即使它是可取的)。 - 重复分配和释放相同大小的内存。 - 您希望使用分配器的类型非常小(例如 char、short、int 等内置类型)。
理论上,一个实现可以利用一个 memory_pool,它每次需要分配实际分配大小的倍数(来自底层内存管理器)。靠得很近的对象更适合任何缓存和/或预取算法。 我已经实现了这样一个内存池,它有一些开销来处理正确的分配、拆分和释放(我们不能释放用户将传递给释放的每个地址。我们只需要释放作为我们拥有的每个内存块开头的地址之前已分配)。
我用以下非常简单的代码测试了这两种情况:
std::list<int, allocator<int>> list;
std::clock_t t = std::clock();
for (int i = 0; i < 1 << 16; ++i)
{
for (int j = 0; j < 1 << 16; ++j)
list.push_back(j);
list.unique();
for (int j = 0; j < 1 << 16; ++j)
list.pop_back();
}
std::cout << (std::clock() - t) / CLOCKS_PER_SEC << std::endl;
std::list 每次调用 allocactor::allocate(1, 0) 时都会调用 push_back。 unique() 确保每个元素都会被触摸并与下一个元素进行比较。
然而,结果令人失望。管理按块分配内存池所需的最小开销大于系统获得的任何可能优势。
你能想出一个可以提高性能的场景吗?
编辑:
当然比std::allocator快很多。
【问题讨论】:
-
请注意包装分配器不能分配数组。
标签: c++ memory-management memory-pool