• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            在高效C++編程中看到一個不錯的內(nèi)存池實現(xiàn)方案,這里共享下,大家看看有什么不足。
            代碼很簡單,如下:
            template<typename T>
            class CMemoryPool
            {
                public:
                    enum { EXPANSION_SIZE = 32};

                    CMemoryPool(unsigned int nItemCount = EXPANSION_SIZE)
                    {
                        ExpandFreeList(nItemCount);
                    }
                    
                    ~CMemoryPool()
                    {
                        //free all memory in the list
                        CMemoryPool<T>* pNext = NULL;
                        for(pNext = m_pFreeList; pNext != NULL; pNext = m_pFreeList)
                        {
                            m_pFreeList = m_pFreeList->m_pFreeList;
                            delete [](char*)pNext;
                        }
                    }

                    void* Alloc(unsigned int /*size*/)
                    {
                        if(m_pFreeList == NULL)
                        {
                            ExpandFreeList();
                        }
                        
                        //get free memory from head
                        CMemoryPool<T>* pHead = m_pFreeList;
                        m_pFreeList = m_pFreeList->m_pFreeList;
                        return pHead;
                    }

                    void Free(void* p)
                    {
                        //push the free memory back to list
                        CMemoryPool<T>* pHead = static_cast<CMemoryPool<T>*>(p);
                        pHead->m_pFreeList = m_pFreeList;
                        m_pFreeList = pHead;
                    }

                protected:
                    //allocate memory and push to the list
                    void ExpandFreeList(unsigned nItemCount = EXPANSION_SIZE)
                    {
                        unsigned int nSize = sizeof(T) > sizeof(CMemoryPool<T>*) ? sizeof(T) : sizeof(CMemoryPool<T>*);
                        CMemoryPool<T>* pLastItem = static_cast<CMemoryPool<T>*>(static_cast<void*>(new char[nSize]));
                        m_pFreeList = pLastItem;
                        for(int i=0; i<nItemCount-1; ++i)
                        {
                            pLastItem->m_pFreeList = static_cast<CMemoryPool<T>*>(static_cast<void*>(new char[nSize]));
                            pLastItem = pLastItem->m_pFreeList;
                        }

                        pLastItem->m_pFreeList = NULL;
                    }

                private:
                    CMemoryPool<T>* m_pFreeList;
            };

            它的實現(xiàn)思想就是每次從List的頭上取內(nèi)存, 如果取不到則重新分配一定數(shù)量; 用完后把內(nèi)存放回List頭部,這樣的話效率很高,因為每次List上可以取到的話,肯定是空閑的內(nèi)存。

            當然上面的代碼只是針對單線程的,要支持多線程的話也很簡單,外面加一層就可以了,
            代碼如下:
            class CCriticalSection
            {
            public:
                CCriticalSection()
                {
                    InitializeCriticalSection(&m_cs);
                }

                ~CCriticalSection()
                {
                    DeleteCriticalSection(&m_cs);
                }

                void Lock()
                {
                    EnterCriticalSection(&m_cs); 
                }

                void Unlock()
                {
                    LeaveCriticalSection(&m_cs);
                }

            protected:
                CRITICAL_SECTION m_cs;
            };

            template<typename POOLTYPE, typename LOCKTYPE>
            class CMTMemoryPool
            {
                public:
                    void* Alloc(unsigned int size)
                    {
                        void* p = NULL;
                        m_lock.Lock();
                        p = m_pool.Alloc(size);
                        m_lock.Unlock();

                        return p;
                    }

                    void Free(void* p)
                    {
                        m_lock.Lock();
                        m_pool.Free(p);
                        m_lock.Unlock();    
                    }

                private:
                    POOLTYPE m_pool;
                    LOCKTYPE m_lock;
            };

            這是我的測試代碼:
            #include <iostream>
            #include <windows.h>

            using namespace std;

            #include "MemoryPool.h"
            #include "MTMemoryPool.h"

            class CTest
            {
            public:
                int m_n;
                int m_n1;

                voidoperator new(size_t size)
                {
                    void* p = s_pool->Alloc(size);
                    return p;
                }

                void operator delete(void* p, size_t size)
                {
                    s_pool->Free(p);
                }

                static void NewPool()
                {
                    //s_pool = new CMemoryPool<CTest>;
                    s_pool = new CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>;
                }

                static void DeletePool()
                {
                    delete s_pool;
                    s_pool = NULL;
                }
                
                //static CMemoryPool<CTest>* s_pool;
                static CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>* s_pool;
            };

            //CMemoryPool<CTest>* CTest::s_pool = NULL;
            CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>* CTest::s_pool = NULL;

            void testFun()
            {
                int i;
                const int nLoop = 10;
                const int nCount = 10000;
                
                for(int j = 0; j<nLoop; ++j)
                {
                    typedef CTest* LPTest;
                    LPTest arData[nCount];
                    for(i=0;i <nCount; ++i)
                    {
                        arData[i] = new CTest;
                    }

                    for(i=0;i <nCount; ++i)
                    {
                        delete arData[i];
                    }
                }
            }

            int main(int argc, char* argv[])
            {
                {
                    unsigned int dwStartTickCount = GetTickCount();

                    CTest::NewPool();

                    testFun();
                    
                    CTest::DeletePool();
                    
                    cout << "total cost" << GetTickCount() - dwStartTickCount << endl;
                }


                system("pause");

                return 0;
            }
            在我機器上測試結(jié)果比系統(tǒng)默認的CRT實現(xiàn)高效N倍。
            posted on 2012-05-05 23:23 Richard Wei 閱讀(18376) 評論(12)  編輯 收藏 引用 所屬分類: C++

            FeedBack:
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2012-05-05 23:55 | zgpxgame
            固定大小的緩沖池策略  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2012-05-06 09:35 | Richard Wei
            @zgpxgame
            是的,適用經(jīng)常分配和釋放的同一類型的對象。
            可變對象大小的內(nèi)存池還要復(fù)雜的多,也沒有很通用的解決方案。
              回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2012-05-07 08:39 | Richard Wei
            @ithaca
            不好意思,有點誤導,應(yīng)該是這本書,
            《提高C++性能的編程技術(shù)》  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2012-06-13 00:23 | 華夏之火
            對于c++類中的這種通過operator new,來使用特制的內(nèi)存池的接口方式,我咋覺得很難受。如果類的內(nèi)存池可由用戶來指定,那就很好了。不過我思考了很久,一直都找不到好的方式,實現(xiàn)出來的效果,總是使用的接口太難看了。最后,我心一橫,需要內(nèi)存分配的對象,全部都是POD類型的,沒有構(gòu)造析構(gòu),這樣用戶想要指定什么內(nèi)存池,就用什么內(nèi)存池  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2012-06-19 17:51 | alias
            用配置文件來指定對象大小和數(shù)量,稍微解決。  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2013-07-29 10:39 | foundwant
            為什么我測試的還不如系統(tǒng)分配的速度快呢?
            int main(int argc,char*argv[])
            {
            unsigned int dwStartTickCount = GetTickCount();
            CTest::NewPool();
            testFun();
            CTest::DeletePool();
            cout << "total cost:" << GetTickCount()-dwStartTickCount <<endl;


            dwStartTickCount = GetTickCount();
            // CTest::NewPool();
            for(int i = 0;i<10;++i)
            {
            int* array[10000];
            for(int j = 0;j<10000;++j)
            {
            array[j] = new int;
            }
            for(int j = 0; j<10000;++j)
            {
            delete array[j];
            }
            }
            // CTest::DeletePool();
            cout << "System Cost:"<< GetTickCount() - dwStartTickCount << endl;

            system("pause");
            return 0;
            }  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2013-07-29 17:56 | Richard Wei
            @foundwant
            確實, 這和分配策略有關(guān)。
            上面的內(nèi)存池適合頻繁的分配和釋放的情況, 但是對于多次連續(xù)分配就不適合了。其他一些內(nèi)存池可參考:http://m.shnenglu.com/weiym/archive/2013/04/08/199238.html  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2014-05-09 13:53 | xzq0102@163.com
            上述代碼有個Bug:
            unsigned int nSize = sizeof( T ) > sizeof( CMemoryPool<T>* ) ? sizeof( T ) : sizeof( CMemoryPool<T>* );

            應(yīng)改為:

            unsigned int nSize = sizeof( T ) > sizeof( CMemoryPool<T>) ? sizeof( T ) : sizeof( CMemoryPool<T>* );

              回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2014-09-23 21:43 | duanyuncanyang
            事實上你的CMemoryPool代碼是有問題的,如果T是一個對象,你上面的代碼沒有辦法調(diào)用T的構(gòu)造函數(shù)來構(gòu)造對象,而是使用強制轉(zhuǎn)化的方式。所以對于T中有虛函數(shù)或者是虛繼承過來的,不調(diào)用構(gòu)造函數(shù)編譯器將無法正確設(shè)置vptr,所以T的對象在調(diào)用虛函數(shù)的時候會發(fā)生錯誤。所以可以這樣改,
            T* Alloc(unsigned int /*size*/)
            {
            if(m_pFreeList == NULL)
            {
            ExpandFreeList();
            }

            //get free memory from head
            CMemoryPool<T>* pHead = m_pFreeList;
            m_pFreeList = m_pFreeList->m_pFreeList;
            return new (pHead) T;
            }  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2014-09-23 22:09 | Richard Wei
            @duanyuncanyang
            memory pool 本身只負責內(nèi)存分配,是給對象的operate new 和operate delete調(diào)用的,具體參見上面的測試代碼  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2015-04-22 18:54 | 方貴深
            @duanyuncanyang不會吧,他這個函數(shù)只是返回一塊內(nèi)存,最外面的new還會在這塊內(nèi)存上調(diào)用構(gòu)造函數(shù),這個應(yīng)該沒錯。  回復(fù)  更多評論
              
            # re: 一個高效的內(nèi)存池實現(xiàn)
            2015-06-27 20:14 | GD
            unsigned int nSize = sizeof(T) > sizeof(CMemoryPool<T>*) ? sizeof(T) : sizeof(CMemoryPool<T>*);

            這句的用意是什么?

            還有為啥不轉(zhuǎn)成static_cast<byte*>(pList)  回復(fù)  更多評論
              
            麻豆一区二区99久久久久| 久久综合狠狠综合久久综合88| 青青久久精品国产免费看| 人妻久久久一区二区三区| 日本高清无卡码一区二区久久| Xx性欧美肥妇精品久久久久久| 久久久噜噜噜www成人网| 亚洲欧洲日产国码无码久久99| 久久久精品无码专区不卡| 亚洲国产成人久久综合碰碰动漫3d | 99久久亚洲综合精品成人| 精品国产青草久久久久福利| 久久综合伊人77777| 51久久夜色精品国产| 99久久国产亚洲高清观看2024| 99久久99久久精品国产| 精品多毛少妇人妻AV免费久久| 日本精品久久久久中文字幕| 18岁日韩内射颜射午夜久久成人| 国产精品99久久久久久猫咪 | 日本久久中文字幕| 色综合久久88色综合天天 | 亚洲人成无码久久电影网站| 精品久久久无码21p发布| AV狠狠色丁香婷婷综合久久| 欧美久久综合性欧美| 精品国产综合区久久久久久| 久久久久香蕉视频| 久久精品综合网| 99久久精品日本一区二区免费| 久久精品国产亚洲AV香蕉| 久久九九亚洲精品| 中文字幕无码久久精品青草| 久久亚洲AV成人无码国产| 欧美伊香蕉久久综合类网站| 亚洲国产婷婷香蕉久久久久久| 久久久噜噜噜久久熟女AA片| 久久精品国产99久久丝袜| 精品国产乱码久久久久久人妻| 久久99精品国产麻豆| 久久精品国产黑森林|