- #include <stdlib.h>
- #include <stdio.h>
- #include <time.h>
- #include <iostream>
- using namespace std;
- class MemPool
- {
- public:
- MemPool();
- ~MemPool();
- void* Alloc();
- void Free(void* p);
-
- private:
- const static int blockSize = 1024;
- const static int itemSize = 16;
-
- struct ItemNode
- {
- ItemNode *next;
- char data[itemSize - sizeof(ItemNode*)];
- };
-
- struct BlockNode
- {
- BlockNode *next;
- ItemNode data[blockSize/itemSize];
- };
-
- ItemNode *freeItemNodeHead;
- BlockNode *memBlockNodeHead;
- };
- MemPool::MemPool():memBlockNodeHead(NULL), freeItemNodeHead(NULL)
- {
- }
- MemPool::~MemPool()
- {
- BlockNode *temp = memBlockNodeHead;
- while(temp)
- {
- memBlockNodeHead = memBlockNodeHead->next;
- delete temp;
- temp = memBlockNodeHead;
- }
- }
- void* MemPool::Alloc()
- {
- if(freeItemNodeHead == NULL)
- {
- BlockNode *tempBlockNode = new BlockNode;
- if(tempBlockNode == NULL)
- {
- perror("allocate memory error!\n");
- exit(1);
- }
-
- if(memBlockNodeHead == NULL)
- {
- memBlockNodeHead = tempBlockNode;
- memBlockNodeHead->next = NULL;
- }
- else
- {
- tempBlockNode->next = memBlockNodeHead;
- memBlockNodeHead = tempBlockNode;
- }
-
- freeItemNodeHead = &(memBlockNodeHead->data[0]);
-
- int i = 0;
- while(i < blockSize/itemSize -1)
- {
- tempBlockNode->data[i].next = &(tempBlockNode->data[i+1]);
- ++i;
- }
-
- tempBlockNode->data[i].next = NULL;
- }
-
- ItemNode *allocItemNode = freeItemNodeHead;
- freeItemNodeHead = freeItemNodeHead->next;
-
- return allocItemNode;
- }
- void MemPool::Free(void* p)
- {
- ItemNode *tempItemNode = static_cast<ItemNode*>(p);
- tempItemNode->next = freeItemNodeHead;
- freeItemNodeHead = tempItemNode;
- }
- int main()
- {
- MemPool pool;
- char *p = NULL;
-
- clock_t start, finish;
-
- double duration;
-
- long i = 0;
-
- start = clock();
-
- while(i < 10000000)
- {
- p = static_cast<char*>(pool.Alloc());
- //p = new char[16];
- ++i;
- pool.Free(p);
- //delete p;
- }
-
- finish = clock();
-
- duration = (double)(finish - start)/CLOCKS_PER_SEC;
-
- cout << "total use " << duration << " seconds" << endl;
-
- system("pause");
-
- return 0;
- }
使用内存池的结果是:
total use 0.245 seconds
使用new,delete操作的结果是:
total use 7.256 seconds
结果相差近30倍,可见使用内存池对系统的性能有很大的提高
MemPool实现源码参见:http://blog.csdn.net/zhangzhenghe/article/details/5437487