我尝试使用Boost.Pool allocator和
vector<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)
typedef basic_string<wchar_t,char_traits<wchar_t>,boost::pool_allocator<wchar_t>> PoolString; vector<PoolString> vec;
- user1149224fast_pool_allocator
,消耗的时间大约是没有任何分配器自定义的3倍。我已经切换了你和我的代码,这样更多的人可以运行它。 - pmr