在下面的代码中,许多每 10 个整数的向量以 60% 的几率被构造,或者一个现有的向量以 40% 的几率被删除。因此,将有许多对new/malloc和删除的调用。由于所有这些向量都是 vector<int>
型,自定义分配器能否帮助减少对new
和delete
的调用,从而提高性能?这个想法是,删除的向量的空间可以被新构建的向量重用。这样的分配器会是什么样子?
注意:这个问题是关于分配器的,它减少了对new
和delete
的调用。
#include <iostream>
#include <vector>
#include <random>
using namespace std;
int main()
{
// Random generator and distribution
mt19937 gen(123456);
uniform_real_distribution<> dis01(0., 1.);
// Make or delete 10E6 vectors.
vector< vector<int> > v; //the inner vectors will make many calls to new and delete
v.reserve(10E5); //assume some size.
for(int i=0; i<10E6; ++i)
{
if(dis01(gen)<0.6) // if true: make new sub-vector
{
v.emplace_back(); //new sub-vector
v.back().reserve(10);
for(int k=0; k<10; ++k)
v.back().emplace_back(k); //fill it with some numbers
}
else // else, delete the last entry if there is one.
if(!v.empty())
v.pop_back();
}
cout<<"v.size()= "<<v.size();
return 0;
}
您可以通过编写分配器来更有效地重用最近释放的内存,尤其是在所有向量的大小均为 10 的情况下,可以获得一些性能。 当然,如果是这种情况,您将通过使用固定大小的对象获得更多性能。 如果向量的分配大小需要动态,那么您的问题就像一般内存分配一样抽象,并且您不太可能改进标准分配器。
与 STL 相比,您根本不可能提高性能,除非您能够利用适用于您的特定案例但不适用于更一般情况的信息。
一个更好的解决方案是不删除向量对象,而只是将它们留在向量中>,维护一个迭代器/指向向量"末端"的指针(递减而不是删除),然后而不是放置一个元素(构造一个向量),你只需推进你的迭代器,测试.end()
,然后根据需要放置, 否则重用旧向量。 这假设你的程序不依赖于构造函数或析构函数的副作用(vector 不依赖于,但你没有告诉我们你的实际用例)。
正如我从 https://en.wikipedia.org/wiki/Allocator_(C%2B%2B) 中了解到的那样,C++分配器减少了对特定容器的分配和取消分配的请求。我认为这意味着创建和删除容器仍然需要调用 new 和 delete。
你可能想看看 https://github.com/gperftools/gperftools。它是malloc的替代品。它声称改进了小对象分配,尤其是在多线程程序中。
针对C++11的。旧标准需要额外的东西在分配器 [1] 中实现。
这是概念验证代码。它运行并求解示例问题,但有几个限制。它仍然演示如何使用自定义分配器来改进在大量std::vector
的场景中的性能创造和破坏。
PoolAlloc.hh
:
template<typename T>
struct MemChunk
{
std::size_t buf_size=0;
T* buf=nullptr;
T* top=nullptr;
std::size_t used=0;
};
template<typename T>
class PoolAllocator
{
public:
using value_type=T;
PoolAllocator();
explicit PoolAllocator(std::size_t);
PoolAllocator(PoolAllocator const&) noexcept;
template<typename U>
PoolAllocator(PoolAllocator<U> const&) noexcept;
PoolAllocator(PoolAllocator&&) noexcept;
PoolAllocator& operator=(PoolAllocator const&)=delete;
PoolAllocator& operator=(PoolAllocator&&)=delete;
~PoolAllocator();
template <typename U>
struct rebind
{
using other=PoolAllocator<U>;
};
T* allocate(std::size_t);
void deallocate(T*, std::size_t) noexcept;
template<typename U1, typename U2>
friend bool operator==(PoolAllocator<U1> const&, PoolAllocator<U2> const&) noexcept;
private:
std::vector<MemChunk<T>>* memory_=nullptr;
int* ref_count_=nullptr;
std::size_t default_buf_size_=0;
};
template<typename T>
PoolAllocator<T>::PoolAllocator():
PoolAllocator{100000} {}
template<typename T>
PoolAllocator<T>::PoolAllocator(std::size_t buf_size):
memory_{new std::vector<MemChunk<T>>},
ref_count_{new int(0)},
default_buf_size_{buf_size}
{
memory_->emplace_back();
memory_->back().buf_size=buf_size;
memory_->back().buf=new T[buf_size];
memory_->back().top=memory_->back().buf;
++(*ref_count_);
}
template<typename T>
PoolAllocator<T>::PoolAllocator(PoolAllocator const& src) noexcept:
memory_{src.memory_},
ref_count_{src.ref_count_},
default_buf_size_{src.default_buf_size_}
{
++(*ref_count_);
}
template<typename T>
PoolAllocator<T>::PoolAllocator(PoolAllocator&& src) noexcept:
memory_{src.memory_},
ref_count_{src.ref_count_},
default_buf_size_{src.default_buf_size_}
{
src.memory_=nullptr;
src.ref_count_=nullptr;
}
template<typename T>
template<typename U>
PoolAllocator<T>::PoolAllocator(PoolAllocator<U> const& src) noexcept:
memory_{src.memory_},
ref_count_{src.ref_count_},
default_buf_size_{src.default_buf_size_}
{
++(*ref_count_);
}
template<typename T>
PoolAllocator<T>::~PoolAllocator()
{
if (ref_count_!=nullptr)
{
--(*ref_count_);
if (*ref_count_==0)
{
if (memory_!=nullptr)
{
for (auto& it : *memory_)
{
delete[] it.buf;
}
delete memory_;
}
delete ref_count_;
}
}
}
template<typename T>
T*
PoolAllocator<T>::allocate(std::size_t n)
{
MemChunk<T>* mem_chunk=&memory_->back();
if ((mem_chunk->used+n)>mem_chunk->buf_size)
{
default_buf_size_*=2;
memory_->emplace_back();
mem_chunk=&memory_->back();
std::size_t buf_size=default_buf_size_;
if (n>default_buf_size_)
{
buf_size=n;
}
mem_chunk->buf_size=buf_size;
mem_chunk->buf=new T[mem_chunk->buf_size];
mem_chunk->top=mem_chunk->buf;
}
T* r=mem_chunk->top;
mem_chunk->top+=n;
mem_chunk->used+=n;
return r;
}
template<typename T>
void
PoolAllocator<T>::deallocate(T* addr, std::size_t n) noexcept
{
MemChunk<T>* mem_chunk=&memory_->back();
if (mem_chunk->used>n and (mem_chunk->top-n)==addr)
{
mem_chunk->used-=n;
mem_chunk->top-=n;
}
}
template<typename U1, typename U2>
bool operator==(PoolAllocator<U1> const& lhs, PoolAllocator<U2> const& rhs) noexcept
{
return (std::is_same<U1, U2>::value and lhs.memory_==rhs.memory_);
}
使用您的示例按以下方式修改:
#include <iostream>
#include <vector>
#include <random>
#include "PoolAlloc.hh"
using namespace std;
int main()
{
// Random generator and distribution
mt19937 gen(123456);
uniform_real_distribution<> dis01(0., 1.);
PoolAllocator<int> palloc{1000000};
// Make or delete 10E6 vectors.
vector< vector<int, PoolAllocator<int>> > v; //the inner vectors will make many calls to new and delete
v.reserve(10E5); //assume some size.
for(int i=0; i<10E6; ++i)
{
if(dis01(gen)<0.6) // if true: make new sub-vector
{
v.emplace_back(palloc); //new sub-vector
v.back().reserve(10);
for(int k=0; k<10; ++k)
v.back().emplace_back(k); //fill it with some numbers
}
else // else, delete the last entry if there is one.
if(!v.empty())
v.pop_back();
}
cout<<"v.size()= "<<v.size();
return 0;
}
对malloc
的调用次数从 ~6e6 下降到 21。总指令数从 3.7e9 下降到 2.5e9(使用 -O3,用valgrind --tool=callgrind
测量)。
有几个实现细节会影响在不同使用情况下的性能。
当前使用多个缓冲区。如果一个已满,则另一个已创建。这样就永远不必重新分配会让你进入一个受伤世界的操作(见评论)。
最大的问题是,如何处理释放的内存。目前使用一种微不足道的方法,该方法仅使释放可供以后使用的内存在缓冲区。对于您的示例,这已经足够了,因为您只需要在缓冲区末尾释放内存。
对于更复杂的方案,您将需要更复杂的机制。需要一些数据结构来存储地址和可用内存块的大小。多个概念是可能的在这里,它们的性能会因具体情况而异它们用于。我怀疑有一个好的一刀切解决方案在这里。
[1] http://howardhinnant.github.io/stack_alloc.html
自定义分配器可能会解决一些问题,但它不是灵丹妙药。这个例子不足以知道最佳解决方案是什么。我将提出一些不同的东西,不是因为它更好,而是因为它在某些情况下可能会更好。
v.resize(10E5, std::vector<int>(10));
而不是
v.reserve(10E5);
但是,您需要一个迭代器来迭代向量上的下一个空闲插槽以及所有这些好东西。
您是否尝试过现有的提升池分配器?
http://theboostcpplibraries.com/boost.pool
我认为,如果要重用"std::vector的对象本身"内存,它应该与放置创建/池有关。
在我看来,自定义分配器实际上只有在您确切知道内存将如何使用时才比标准分配器更有优势。 通常,您正在进行大小/性能权衡,而自定义分配器允许您控制此决定。
如果在示例中,您可以为每个列表使用页面大小块,那么您可以保留一个免费页面列表,并在所有未来的分配中分发它们。 如果您实际上每个列表中只有十个整数,这将产生很大的内存开销,但如果列表更大,并且可以在不调用每个整数的 new 或删除的情况下完成,这可能是一个巨大的胜利。这实质上是为每个列表创建一个固定大小的内存池。 完成列表后,您只需将页面放回空闲列表中并将其用于下一个列表。