数据结构内存管理c++实现
作者:网络转载 发布时间:[ 2014/3/31 10:36:25 ] 推荐标签:c++ 内存 数据
private:
void* memory_;
size_t memory_size_; // memory total size;
memblock_head_t* freelist_;
#ifdef EANBLE_MULTI_THREAD
std::mutex mtx_;
#endif
};
int main(int argc, char** argv)
{
/*apr_allocator_t* allocator;
apr_allocator_create(&allocator);
apr_memnode_t* node = apr_allocator_alloc(allocator, SZ(3, k));
apr_allocator_free(allocator, node);
node = apr_allocator_alloc(allocator, SZ(3, k));*/
int times = 1000000;
mempool pool;
char* p1 = (char*)pool.allocate(25);
strcpy(p1, "hello world");
char* p2 = (char*)pool.allocate(25);
char* p3 = (char*)pool.allocate(25);
char* p4 = (char*)pool.allocate(25);
pool.deallocte(p2);
pool.deallocte(p4);
pool.deallocte(p3);
pool.deallocte(p1);
double end[4];
clock_t start = clock();
for(int i = 0; i < times; ++i)
{
void* p = malloc(rrand(sizeof(int), 8192 * 2));
if(p)
free(p);
}
end[0] = (clock() - start) / (double)CLOCKS_PER_SEC;
start = clock();
for(int i = 0; i < times; ++i)
{
void* p = pool.allocate(rrand(sizeof(int), 8192 * 2));
if(p)
pool.deallocte(p);
}
end[1] = (clock() - start) / (double)CLOCKS_PER_SEC;
start = clock();
for(int i = 0; i < times; ++i)
{
void* p = malloc(sizeof(int));
if(p)
free(p);
}
end[2] = (clock() - start) / (double)CLOCKS_PER_SEC;
/*start = clock();
for(int i = 0; i < times; ++i)
{
apr_memnode_t* p = apr_allocator_alloc(allocator, rrand(sizeof(int), 8192 * 2));
if(p)
apr_allocator_free(allocator, p);
}
end[3] = (clock() - start) / (double)CLOCKS_PER_SEC;*/
printf("malloc/free random size %d times, use %lf seconds
", times, end[0]);
printf("mempool allocate/deallocte random size %d times, use %lf seconds
", times, end[1]);
printf("malloc/free fixed size %d times, use %lf seconds
", times, end[2]);
//printf("apr alloc/free random size %d times, use %lf seconds
", times, end[3]);
/* result at win32 release:
malloc/free random size 1000000 times, use 7.251000 seconds
mempool allocate/deallocte random size 1000000 times, use 0.031000 seconds
malloc/free fixed size 1000000 times, use 0.360000 seconds
apr alloc/free random size 1000000 times, use 0.031000 seconds
*/
/* result at linux release
malloc/free random size 1000000 times, use 0.070000 seconds
mempool allocate/deallocte random size 1000000 times, use 0.030000 seconds
malloc/free fixed size 1000000 times, use 0.040000 seconds
apr alloc/free random size 1000000 times, use 0.040000 seconds
*/
#ifdef _WIN32
system("pause");
#endif
return 0;
}

sales@spasvo.com