使用Boost.Pool分配器与vector<wstring>

3
我尝试使用Boost.Pool allocatorvector<wstring>一起使用,希望可以比一般的vector<wstring>分配方式获得更好的性能(像这些一样快速)。

然而,事实上,使用Boost.Pool后我得到的结果却更差,例如:

  • 对于15000次迭代,普通分配的vector<wstring>显示0 ms,而使用Boost.Pool的耗时为5900毫秒;

  • 对于5000000次迭代,默认分配器需要约1300毫秒完成循环,而使用boost::pool_allocator则需要很长时间(一分钟后我使用了Ctrl+C退出了程序)。

下面是我编写的C++代码基准测试:

//////////////////////////////////////////////////////////////////////////
// TestBoostPool.cpp
// Testing vector<wstring> with Boost.Pool
//////////////////////////////////////////////////////////////////////////


#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

// To avoid linking with Boost Thread library
#define BOOST_DISABLE_THREADS

#include <boost/pool/pool_alloc.hpp>
#include <boost/timer/timer.hpp>

using namespace std;

void Test()
{
  // Loop iteration count
  static const int count = 5*1000*1000;

  //
  // Testing ordinary vector<wstring>
  //
  cout << "Testing vector<wstring>" << endl;
  {
    boost::timer::auto_cpu_timer t;
    vector<wstring> vec;
    for (int i = 0; i < count; i++)
    {
      wstring s(L"I think therefore I am; just a simple test string.");
      vec.push_back(s);
    }
  }

  //
  // Testing vector<wstring> with Boost.Pool
  //
  cout << "Testing vector<wstring> with Boost.Pool" << endl;
  {
    boost::timer::auto_cpu_timer t;
    typedef basic_string<wchar_t, char_traits<wchar_t>, 
      boost::fast_pool_allocator<wchar_t>> PoolString;

    vector<PoolString> vec;
    for (int i = 0; i < count; i++)
    {
      PoolString s(L"I think therefore I am; just a simple test string.");
      vec.push_back(s);
    }

    // Release pool memory
    boost::singleton_pool<boost::fast_pool_allocator_tag, sizeof(wchar_t)>::release_memory();
  }

  cout << endl;
}


int main()
{
    const int exitOk = 0;
    const int exitError = 1;

    try
    {
        Test();
    }
    catch(const exception & e)
    {
        cerr << "\n*** ERROR: " << e.what() << endl;
        return exitError;
    }

    return exitOk;
}

我是否错误地使用了 Boost.Pool?我在这里缺失了什么?

(我使用的是带有 Boost 1.49.0 的 VS2010 SP1)


你看到了什么时间(如果你的时间很短,GetTickCount可能会非常不准确)?只是猜测:boost::pool是线程安全的吗?你是否因锁而受到影响? - David
@Dave:我编辑了原始问题,以添加关于时间的更多信息。我甚至不确定自己是否正确地使用了 Boost.Pool,因为在使用它时应用程序似乎被阻塞了。我只是这样做了:typedef basic_string<wchar_t,char_traits<wchar_t>,boost::pool_allocator<wchar_t>> PoolString; vector<PoolString> vec; - user1149224
1
我将你的代码移植为独立于Windows并获得相同的结果。使用fast_pool_allocator,消耗的时间大约是没有任何分配器自定义的3倍。我已经切换了你和我的代码,这样更多的人可以运行它。 - pmr
我相信pool_allocator只能加速没有外部资源的对象容器的分配。例如,int列表或char向量是可以的,但不适用于字符串向量。 - ggg
1个回答

11

请注意 Boost.Pool 不是为此用途而设计或优化的 - 它专门为大量固定大小的块设计,例如在列表(甚至映射或设置)中发生的情况,它并不真正针对变量大小的块进行快速性能优化,如字符串或向量中发生的情况。


感谢澄清。基于这些信息,我在这里开了一个新的帖子。 - user1149224

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接