简单内存池

System Call

先测试系统调用new/delete的用时。

#include <iostream>
#include <time.h> 
using namespace std;
timespec diff(timespec start, timespec end)
{
    timespec temp;
    if((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
    } 
    else 
    {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

class TestClass
{
private:
    char m_chBuf[4096];
};

int main()
{
    timespec time1, time2;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    for(unsigned int i=0; i< 0x5fffff; i++)
    {
        TestClass *p = new TestClass;
        delete p;
    }
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
    cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
}

用时为0:604124400。

Memory Pool

再测试简单内存池。

#include <iostream>
#include <time.h> 
using namespace std;

char buf[4100]; //已分配内存

class TestClass
{
public:
    void* operator new(size_t)
    {
        return (void*)buf;
    }
    void operator delete(void* p)
    {

    }
private:
    char m_chBuf[4096];
};

timespec diff(timespec start, timespec end)
{
    timespec temp;
    if((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
    } 
    else 
    {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

int main()
{
    timespec time1, time2;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    for(unsigned int i=0; i< 0x5fffff; i++)
    {
        TestClass *p = new TestClass;
        delete p;
    }
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
    cout<<diff(time1,time2).tv_sec<<":"<<diff(time1,time2).tv_nsec<<endl;
}

用时为0:39420791。两者相差20倍。

其实系统的new是在堆上分配资源,每次执行都会分配然后销毁。

而简单内存池在开始在全局/静态存储区分配资源,一直存在。每次重载的new调用只是返回了buf的地址,所以快。

只有当程序频繁地用系统调用malloc/free或者new/delete分配内存时,内存池有价值。

Reference

[1].http://www.codeproject.com/Articles/27487/Why-to-use-memory-pool-and-how-to-implement-it

[2].http://blog.chinaunix.net/uid-12461657-id-3183111.html

你可能感兴趣的:(简单内存池)