c++ - 无序自定义对象集的 boost 池

标签 c++ boost pool allocator

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

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

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

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

最佳答案

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.584661 秒墙,0.560000 秒用户 + 0.010000 秒系统 = 0.570000 秒 CPU (97.5%) 1000000

关于c++ - 无序自定义对象集的 boost 池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178480/

相关文章:

c++ - 如何最好地利用 wcsdup?

可变序列 : How to create similar code block for each argument/type? 的 C++ 模板和代码生成

c++ - #include<boost> 没有这样的文件或目录

python - 不能 pickle 函数

mysql - 握手不活动超时 : nodejs 6. 10.0 mysql pool.queryAsync

c++ - 在不复制代码的情况下从工厂实例化对象(例如炮塔)的草图(即原型(prototype))

c++ - 使用模板函数对列表容器进行排序

c++计时器稍后调用函数/方法?

c++ - 捕获 boost 线程中断和退出线程的正确方法

python - 获取对 Python dict 键的引用