doing5552

记录每日点滴,不枉人生一世

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  73 Posts :: 0 Stories :: 94 Comments :: 0 Trackbacks

公告

常用链接

留言簿(24)

我参与的团队

最新随笔

搜索

  •  

积分与排名

  • 积分 - 452046
  • 排名 - 47

最新随笔

最新评论

阅读排行榜

评论排行榜

从最简单的入手

1.实现一个固定大小的allocator

//分配固定大小内存块的模板类,内部缓存算法自己实现了,

//我用的是预分配+回收cache链

//即分配时先检查回收链有无数据,无的话每次分配n*size个块,然后返回其中一个,直到该块用完后继续分配

//释放时直接加入回收链即可

//好处是速度够块,但是浪费空间可能就比较大了

template <size_t size> class Fix_Allocator{

void* alloc(size_t size);

void free(void*p);

typedef     Fix_Allocator me;

static me Instance;

};

提供一个给host class用的impl template

template <class Host> class new_op{

void* operator new(size_t size);

//........

};

template < 
   typename Host
   >
inline void* new_op<Host>:: operator new(size_t size){
 return Fix_Allocator<sizeof(Host)>::Instance.alloc(size);
}

然后所有需要内存池的类继承new_op即可

class cls_usePool:public new_op<cls_usePool>{

.........

};

2.改进

以上方法的不足,大小近似的类不能共享内存池,如sizeof(clsA)==11,sizeof(clsB)==12,

内存池并不能提高程序太多效率.

我用的办法是将所有分配大小对齐到2的冥(这样最大内存占用将会接近原来的一倍,考虑(17,33这样大小的对像很多的情况)

解决方法如下

template <bool flag, typename T, typename U>
struct TypeSelectT
{
private:
 template<bool>
 struct In
 { typedef T Result; };

 template<>
 struct In<false>
 { typedef U Result; };

public:
 typedef typename In<flag>::Result Result;
};

#define countof(x) (sizeof(x)/sizeof(x[0]))

template <int x,int y>
struct extr{
protected:
 template <int x1>
 struct imp{
  enum {
   next=(x1+y-1)/y,
  };
  enum {Result=1+imp<next>::Result};
 };

 template <>struct imp<1>{
  enum {Result=0};
 };

public:
 enum {Result=imp<x>::Result};
};

template <int x,int y>
struct pwr{
protected:
 template <int y1>
 struct imp{
  enum{
   next=y1-1
  };
  enum{
   Result=x*imp<next>::Result
  };
 };
 template<> struct imp<0>{
  enum{
   Result=1
  };
 };

public:
 enum{
  Result=imp<y>::Result
 };
};

template <int size>struct allocIdx{
 template <int idx> struct table{
//  enum{  }
  struct accept{
   enum{ Result=0};
  };
  struct Overflow{
   enum{ Result =1};
  };
  enum {
   k
//   Result =TypeSelectT< (idx>=0)&&(idx<countof(allocTable)),accept,Overflow>::Result::Result
  };
 };

};

先用extr算sizeof(cls)最接近2的多少次冥n,然后用pwr计算2的n次冥的值

最后用n查allocidx表得到该大小下,内存块的cache数.

最后将这些值传递给new_op的方法

这样就做到了11 12 13大小的对像全部共享16的allocator,而且是静态绑定的.

posted on 2010-02-22 00:03 doing5552 阅读(427) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理