为无序自定义对象集提升池

Boost pool for unordered set of custom objects

本文关键字:对象 无序 自定义      更新时间:2023-10-16

我很难找到一个例子。我的代码如下所示:

typedef boost::unordered_set<CustomObject, boost::hash<CustomObject>, 
  CustomObjectEqual, allocator<CustomObject> > CustomObjectSet;

我尝试直接使用fast_pool_allocator,但这会导致编译器错误(使用 std::allocator 有效(。我的问题是:

  1. 是否需要为自定义对象创建自定义分配器?
  2. 这会提高我的程序速度吗?

问题 1:是否需要为自定义对象创建自定义分配器?

不。它将在没有它的情况下编译。分配器使用默认参数。在下面的示例中,这些是相同的:

using fast_allocator = boost::fast_pool_allocator<
    CustomObject,
    boost::default_user_allocator_new_delete,
    boost::mutex,
    32,
    0>;
using fast_allocator = boost::fast_pool_allocator<CustomObject>;

#include <boost/unordered_set.hpp>
#include <boost/pool/pool.hpp>
#include <boost/pool/pool_alloc.hpp>
struct CustomObject {
    CustomObject(std::size_t value)
        : value(value)
    {
    }
    std::size_t value;
};
struct CustomObjectKeyEq {
    bool operator()(CustomObject const& l, CustomObject const& r) const 
    {
        return l.value == r.value;
    }
};
std::size_t hash_value(CustomObject const& value)
{
    return value.value;
}
int main()
{
    typedef boost::unordered_set<CustomObject,
                                 boost::hash<CustomObject>,
                                 CustomObjectKeyEq> StandardObjectSet;
    StandardObjectSet set1;
    set1.insert(10);
    set1.insert(20);
    set1.insert(30);
    using fast_allocator = boost::fast_pool_allocator<CustomObject>;
    typedef boost::unordered_set<CustomObject,
                                 boost::hash<CustomObject>,
                                 CustomObjectKeyEq,
                                 fast_allocator> CustomObjectSet;
    CustomObjectSet set2;
    set2.insert(10);
    set2.insert(20);
    set2.insert(30);
    return 0;
}

问题 2:这会提高我的程序速度吗?

通常,您必须对其进行测量。它对上述示例没有重大影响。在 set1 中插入 100 万个对象需要:

0.588423s 墙上,0.570000s 用户 + 0.020000s 系统 = 0.590000s CPU (100.3%(

并进入 set2:

0.584661s 墙上,0.560000s 用户 + 0.010000s 系统 = 0.570000s CPU (97.5%(1000000