推荐日志

自己封装了一个NedAllocator,底层使用nedmalloc

[ 2010-01-20 14:36:40 | 作者: Admin ]
字体大小: | |
这里是对nedmalloc的简介,来自http://www.nedprod.com/programs/portable/nedmalloc/

nedmalloc is a VERY fast, VERY scalable, multithreaded memory allocator with little memory fragmentation. It is faster in real world code than Hoard, faster than tcmalloc, faster than ptmalloc2 and it scales with extra processing cores better than Hoard, better than tcmalloc and better than ptmalloc2 or ptmalloc3. Put another way, there is no faster portable memory allocator out there! Unlike other allocators, it is written in C and so can be used anywhere and it also comes under the Boost software license which permits commercial usage.

在这里我就不翻译了,可惜他是C代码,上层应用很麻烦了,于是我将它封装成了一个NedAllocatorObject.Lib,方便大家使用。

要封装nedmalloc, 先实现一个NedAllocatorImpl
NedAllocatorImpl.h代码如下
#ifndef _NEDALLOCATOR_IMPL_H_
#define _NEDALLOCATOR_IMPL_H_

class NedAllocatorImpl
{
public:
  static void* allocBytes(size_t count);
  static void deallocBytes(void* ptr);
  static void* allocBytesAligned(size_t align, size_t count);
  static void deallocBytesAligned(size_t align, void* ptr);
};

#endif //_NEDALLOCATOR_IMPL_H_
实现如下(NedAllocatorImpl.cpp)
#include "NedAllocatorImpl.h"
#include "nedmalloc.c"

void* NedAllocatorImpl::allocBytes(size_t count)
{
  void* ptr = nedalloc::nedmalloc(count);
  return ptr;
}

void NedAllocatorImpl::deallocBytes(void* ptr)
{
  if(!ptr)
    return;

  nedalloc::nedfree(ptr);
}

void* NedAllocatorImpl::allocBytesAligned(size_t align, size_t count)
{
  const size_t SIMD_ALIGNMENT = 16;
  void* ptr = align ? nedalloc::nedmemalign(align, count)
    : nedalloc::nedmemalign(SIMD_ALIGNMENT, count);
  
  return ptr;
}

void NedAllocatorImpl::deallocBytesAligned(size_t align, void* ptr)
{
  if (!ptr)
    return;
  
  nedalloc::nedfree(ptr);
}
最后我们在封装成一个NedAllocatedObject
#ifndef _NEDALLOCATED_OBJECT_H_
#define _NEDALLOCATED_OBJECT_H_

#include "NedAllocatorImpl.h"

class NedAllocatedObject
{
public:
  explicit NedAllocatedObject()
  {

  }
  ~NedAllocatedObject()
  {

  }

  void* operator new(size_t sz)
  {
    return NedAllocatorImpl::allocBytes(sz);
  }

  /// placement operator new
  void* operator new(size_t sz, void* ptr)
  {
    return ptr;
  }

  void* operator new[] ( size_t sz )
  {
    return NedAllocatorImpl::allocBytes(sz);
  }

  void operator delete( void* ptr )
  {
    NedAllocatorImpl::deallocBytes(ptr);
  }

  void operator delete( void* ptr, void* )
  {
    NedAllocatorImpl::deallocBytes(ptr);
  }

  void operator delete[] ( void* ptr )
  {
    NedAllocatorImpl::deallocBytes(ptr);
  }
};

#endif //_NEDALLOCATED_OBJECT_H_
源代码以及测试代码如下:
点击下载

测试结果:
当执行80000000次,创建和销毁一个不带NedAllocator和带NedAllocator的类。
未使用NedAllocator, 耗时12625毫秒。
使用NedAllocator,耗时2985毫秒。

时间缩减了76%
[最后修改由 Admin, 于 2010-01-20 16:06:34]
评论Feed 评论Feed: http://www.azure.com.cn/feed.asp?q=comment&id=422

浏览模式: 显示全部 | 评论: 1 | 引用: 0 | 排序 | 浏览: 1880
Admin
[ 2010-02-14 22:59:12 ]
呵呵,的确仿照了他的封装方式。

此日志不可发表评论.
ħ˽ ħ˽