3.3 测试3:反复申请和释放C++对象
C++对象在动态申请和释放时,不仅要进行内存操作,同时还要调用构造和析购函数。因此有必要对C++对象也进行内存池的测试。
代码如下:
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <vector>
#include <boost/pool/pool.hpp>
#include <boost/pool/object_pool.hpp>
using namespace std;
using namespace boost;
const int MAXLENGTH = 500000;
class A
{
public:
A()
{
m_i++;
}
~A( )
{
m_i--;
}
private:
int m_i;
};
int main ( )
{
object_pool<A> q;
clock_t clock_begin = clock();
for (int i = 0; i < MAXLENGTH; ++i)
{
A* a = q.construct();
q.destroy(a);
}
clock_t clock_end = clock();
cout<<"程序运行了 "<<clock_end-clock_begin<<" 个系统时钟"<<endl;
clock_begin = clock();
for (int i = 0; i < MAXLENGTH; ++i)
{
A* a = new A;
delete a;
}
clock_end = clock();
cout<<"程序运行了 "<<clock_end-clock_begin<<" 个系统时钟"<<endl;
return 0;
}
#include <iostream>
#include <ctime>
#include <vector>
#include <boost/pool/pool.hpp>
#include <boost/pool/object_pool.hpp>
using namespace std;
using namespace boost;
const int MAXLENGTH = 500000;
class A
{
public:
A()
{
m_i++;
}
~A( )
{
m_i--;
}
private:
int m_i;
};
int main ( )
{
object_pool<A> q;
clock_t clock_begin = clock();
for (int i = 0; i < MAXLENGTH; ++i)
{
A* a = q.construct();
q.destroy(a);
}
clock_t clock_end = clock();
cout<<"程序运行了 "<<clock_end-clock_begin<<" 个系统时钟"<<endl;
clock_begin = clock();
for (int i = 0; i < MAXLENGTH; ++i)
{
A* a = new A;
delete a;
}
clock_end = clock();
cout<<"程序运行了 "<<clock_end-clock_begin<<" 个系统时钟"<<endl;
return 0;
}
测试结果如下:
结论:在反复申请和释放50万个C++对象的情况下,使用内存池耗时是使用new耗时的112.03%。这是因为内存池的construct和destroy函数增加了函数调用次数的原因。这种情况下使用内存池并不能获得性能上的优化。