Skip to content

Instantly share code, notes, and snippets.

@hi2p-perim
Created August 5, 2014 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hi2p-perim/cb9c2ca9e6489a0f93af to your computer and use it in GitHub Desktop.
Save hi2p-perim/cb9c2ca9e6489a0f93af to your computer and use it in GitHub Desktop.
Simple performance test of boost::pool
#include <iostream>
#include <boost/pool/object_pool.hpp>
#include <vector>
#include <chrono>
class Pool
{
public:
virtual ~Pool() {}
virtual int* Allocate() = 0;
virtual void Release(int* v) = 0;
};
class VectorPool : public Pool
{
public:
static const int AllocateCount = 1<<10;
public:
virtual int* Allocate()
{
if (free.empty())
{
// Allocate some
for (int i = 0; i < AllocateCount; i++)
{
allocated.push_back(new int);
free.push_back(allocated.back());
}
}
// Last element of free list
auto* v = free.back();
free.pop_back();
return v;
}
virtual void Release( int* v )
{
free.push_back(v);
}
private:
std::vector<int*> allocated;
std::vector<int*> free;
};
class BoostPool : public Pool
{
public:
virtual int* Allocate()
{
return pool.construct();
}
virtual void Release( int* v )
{
pool.destroy(v);
}
private:
typedef boost::object_pool<int> PoolType;
PoolType pool;
};
void Run(const std::string& name, Pool& pool)
{
int Count = 1<<19;
auto start = std::chrono::high_resolution_clock::now();
std::vector<int*> vs;
for (int i = 0; i < Count; i++)
{
// Allocate
for (int j = 0; j < 100; j++)
{
vs.push_back(pool.Allocate());
}
// Release
for (int j = 0; j < 10; j++)
{
pool.Release(vs.back());
vs.pop_back();
}
}
auto end = std::chrono::high_resolution_clock::now();
double elpased = (double)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() / 1000.0;
std::cout << name << " " << elpased << "s" << std::endl;
};
int main()
{
Run("vector", VectorPool());
Run("boost ", BoostPool());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment