Monday, May 31, 2010

How to use LFH

작년에 메모리 할당자 성능체크 하느라 만들었던 코드인데,
http://eeodl.blogspot.com/2009/04/benchmark-of-memory-allocators.html

I wrote this code last year to check a performance of a couple of memory allocators,

걍 회사 하드에 있던 거 백업용으로 여기다가도 올려놓음.
It just is on office computer, so I post it to remember.

리마인드 시켜준 경만옹께 감사를.
Thanks NomoreID for reminding this.

주의 : 이 코드는 예외 처리가 매우 간단하게 되어 있으므로 가져다쓰실 분은 잘 고쳐서 쓰시기 바랍니다.
Note : You'd better enhance an exception handling if you take this code, because its exception handling is too simple.

#include 

class ActorHeap : public ActorInterface
{
public:
 ActorHeap() : initial_size_(0), use_lfh_(0), heap_(0) {;}
 ActorHeap(size_t initial_size, bool use_lfh) : initial_size_(initial_size), use_lfh_(use_lfh), heap_(0) {;}

 ~ActorHeap()
 {
  if (IsValid() == false)
   return;

  HeapDestroy(heap_);
 }

 void Init()
 {
  heap_ = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, initial_size_, 0);
  if (!heap_)
  {
   printf("HeapCreate failed. (%d)\n", GetLastError());
   return;
  }

  if (use_lfh_)
  {
   ULONG HeapFragValue = 2; // enable low fragmentation heap
   if (!HeapSetInformation(heap_, HeapCompatibilityInformation, &HeapFragValue, sizeof(HeapFragValue)))
   {
    printf("LFG initialization failed. (%d)\n", GetLastError());
   }
  }
 }

 void* Alloc(size_t size)
 {
  if (IsValid() == false)
   return NULL;

  void* block = (void*)HeapAlloc(heap_, HEAP_ZERO_MEMORY, size);
  return block;
 }

 void Free(void* block)
 {
  if (IsValid() == false)
   return;

  BOOL result = HeapFree(heap_, 0, block);
  if (!result)
  {
   printf("HeapFree failed.\n");
  }
 }

 bool IsValid() { return heap_ != NULL; }

private:
 size_t initial_size_;
 bool use_lfh_;

 HANDLE heap_;
};

No comments:

Post a Comment