Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Last active December 11, 2015 10:28
Show Gist options
  • Save hadashiA/4587019 to your computer and use it in GitHub Desktop.
Save hadashiA/4587019 to your computer and use it in GitHub Desktop.
固定サイズのメモリアロケータ2 (好きなクラスを扱える)
#include <stdlib.h>
#include <cstddef>
template <typename T>
class MemoryPool {
public:
MemoryPool(size_t size=EXPANSION_SIZE) {
ExpandTheFreeList(size);
}
~MemoryPool() {
for (MemoryPool<T> *next_ptr = next; next_ptr != NULL; next_ptr = next) {
next = next->next;
delete[] next_ptr;
}
}
void *Alloc(size_t size) {
if (!next) {
ExpandTheFreeList();
}
MemoryPool<T> *head = next;
next = head->next;
return head;
}
void Free(void *doomed) {
MemoryPool<T> *head = static_cast<MemoryPool<T> *>(doomed);
head->next = next;
next = head;
}
MemoryPool<T> *next;
private:
enum { EXPANSION_SIZE = 32 };
void ExpandTheFreeList(int how_many=EXPANSION_SIZE);
};
template <typename T>
void MemoryPool<T>::ExpandTheFreeList(int how_many) {
size_t size = (sizeof(T) > sizeof(MemoryPool<T> *) ?
sizeof(T) : sizeof(MemoryPool<T> *));
MemoryPool<T> *runner = static_cast<MemoryPool<T> *>(malloc(size));
next = runner;
for (int i = 0; i < how_many; ++i) {
runner->next = static_cast<MemoryPool<T> *>(malloc(size));
runner = runner->next;
}
runner->next = NULL;
}
class Rational {
public:
Rational(int n = 0, int d = 1) : n_(n), d_(d) {};
void *operator new(size_t size) {
return __pool->Alloc(size);
}
void operator delete(void *doomed, size_t size) {
__pool->Free(doomed);
}
static void NewMemPool() { __pool = new MemoryPool<Rational>; }
static void PurgeMemPool() { delete __pool; }
// int n() { return n_; }
// int d() { return d_; }
private:
static MemoryPool<Rational> *__pool;
int n_; // 分子
int d_; // 分母
};
MemoryPool<Rational> *Rational::__pool = NULL;
int main(int argc, char **argv) {
Rational *array[1000];
Rational::NewMemPool();
for (int j = 0; j < 500; ++j) {
for (int i = 0; i < 1000; ++i) {
array[i] = new Rational(i);
}
for (int i = 0; i < 1000; ++i) {
delete array[i];
}
}
return 0;
}
// ./version_1 0.01s user 0.00s system 85% cpu 0.018 total
// ./version_2 0.02s user 0.00s system 86% cpu 0.022 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment