日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

BOOST内存管理(一) --- boost::object_pool

發(fā)布時間:2024/4/11 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 BOOST内存管理(一) --- boost::object_pool 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

boost pool是個不錯的庫,可以省點內存管理功夫,內存池分配內存,還可以速度上比malloc更快一些。 boost::object_pool主要針對,對象的內存分配,他可以像使用new 一樣來創(chuàng)建對象,對象的內存放在object_pool里面。 實際上object_pool使用pool類,代碼上是object_pool繼承pool類,object_pool比pool多些什么呢,多的就是new 比malloc多的那些內容. object_pool::construct完成類的內存分配和建構,object_pool::destroy完成類的析構和內存釋放。

看看實際例子:

#include "stdafx.h" #include <malloc.h> #include <boost/pool/object_pool.hpp> #include <boost/serialization/singleton.hpp> #include <boost/thread/mutex.hpp> #include <boost/timer.hpp>class ObjectMgr; typedef boost::unique_lock<boost::mutex> WriteLock; typedef boost::serialization::singleton<ObjectMgr> ObjectMgrFactory;struct myObject {int a;char b;myObject (){a=0;b=0;} };class ObjectMgr { public:myObject* CreateNewObject(myObject o){WriteLock wl(mt);return pool.construct(o);}void free(myObject *po){WriteLock wl(mt);if (pool.is_from(po)){pool.destroy(po);}}private:boost::object_pool<myObject> pool;boost::mutex mt; };int _tmain(int argc, _TCHAR* argv[]) {boost::timer t;for (int i=0;i<20*1024*1024;i++){myObject to;to.a = 2*i;to.b = i;//方式一: objectpool debug:14.553秒 260兆 release:0.674秒 260兆//ObjectMgrFactory::get_mutable_instance().CreateNewObject(to);//方式二: new debug:14.91秒 1420兆 release:11.815秒 610兆//myObject *pmyObject = new myObject(to);//方式三: malloc debug:14.926秒 1400兆 release:11.737秒 630兆//myObject *pmyObject = (myObject *)malloc(sizeof(myObject));//方式四: pool debug:59.235秒 0兆 release:22.116秒 630兆boost::pool<> pObj(sizeof(myObject));myObject *pmyObject = (myObject *)pObj.malloc();}std::cout << "use time "<<t.elapsed()<<std::endl;return 0; }

總結:

1.無論哪種方式的申請內存,占用空間都比有用空間大點,實際有用空間:8字節(jié) * 20*1024*204 = 160兆

2.new和malloc無論在debug還是release下,占用內存資源和CPU資源都差不多

3.使用boost中的object_pool無論從內存消耗還是從速率上來講都比new和malloc好,尤其是使用release的時候分配資源的速度

4.在操作大數(shù)據(jù)的時候,最好使用boost中的boost_pool




總結

以上是生活随笔為你收集整理的BOOST内存管理(一) --- boost::object_pool的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。