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

Boost pool for unordered set of custom objects

我很难为此找到示例。我的代码如下所示:

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

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

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

Question 1: Do I need to create a custom allocator for CustomObject?

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

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;
}

Question 2: Does this increase the speed of my program?

一般情况下,一定要量一下。它对上面的例子没有重大影响。将一百万个对象插入 set1 花费:

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

并进入 set2:

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