最近测试了一下boost线程池,向大家公布一下测试结果,本测试在单线程环境下进行,
boost::pool实用单线程内存方法
boost::singleton_pool适用多线程内存访问
测试代码如下
struct Student
{
char name[8];
};
void heapAllocate()
{
CExecTimer timer;
Student* array[1000];
for (int i=0;i<5000;i++)
{
for (int j=0;j<1000;j++)
{
array[j]=new Student;
}
for (int j=0;j<1000;j++)
{
delete array[j];
}
}
}
void boostAllocate()
{
boost::pool<> student_pool(sizeof(Student));
CExecTimer timer;
Student* array[1000];
for (int i=0;i<5000;i++)
{
for (int j=0;j<1000;j++)
{
array[j]=(Student*)student_pool.malloc();
}
for (int j=0;j<1000;j++)
{
student_pool.free(array[j]);
}
}
}
typedef struct singleton_pool_tag
{
}singleton_pool_tag;
typedef boost::singleton_pool<singleton_pool_tag,sizeof(Student)> global;
void boostSingletonAllocate()
{
CExecTimer timer;
Student* array[1000];
for (int i=0;i<5000;i++)
{
for (int j=0;j<1000;j++)
{
array[j]=(Student*)global::malloc();
}
for (int j=0;j<1000;j++)
{
global::free(array[j]);
}
}
}
其中更改name数组的大小来设置分配单元大小
分配单元大小 | 普通堆分配用时 | boost::pool用时 | boost::singleton_pool用时 |
8字节 | 2620 milli seconds | 1420 milli seconds | 4493 milli seconds |
分配单元大小 | 普通堆分配用时 | boost::pool用时 | boost::singleton_pool用时 |
128字节 | 2871 milli seconds | 1419 milli seconds | 4508 milli seconds |
分配单元大小 | 普通堆分配用时 | boost::pool用时 | boost::singleton_pool用时 |
256字节 | 3136 milli seconds | 1419 milli seconds | 4509 milli seconds |
1K | 4306 milli seconds | 1435 milli seconds | 4539 milli seconds |
2K | 9048 milli seconds | 1451 milli seconds | 4555 milli seconds |
分配单元大小 | 普通堆分配用时 | boost::pool用时 | boost::singleton_pool用时 |
4K | 20671 milli seconds | 1779 milli seconds | 4930 milli seconds |
分配单元大小 | 普通堆分配用时 | boost::pool用时 | boost::singleton_pool用时 |
8K | 20671 milli seconds | 1779 milli seconds | 4930 milli seconds |
有以上数据分析出,boost::pool性能始终最优(因其无锁),当分配单元小于1K时,boost:: singleton_pool性能甚至比不过正常的内存分配,当分配单元大于1K时,
boost::singleton_pool的优势才会逐渐显示
若有同学认为有需要探讨的地方,一定要留言哦!
PS, 今天在自己的机器上又测试了一下,临界值变为2K,faint!