Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace nall {
- namespace memory {
- template<unsigned Count, unsigned Size>
- struct pool {
- signed* list = nullptr;
- uint8_t* data = nullptr;
- unsigned cursor = 0;
- pool() {
- list = (signed*)memory::allocate(Count * sizeof(signed));
- data = (uint8_t*)memory::allocate(Count * Size);
- for(unsigned n = 0; n < Count; n++) list[n] = n;
- }
- ~pool() {
- memory::free(list);
- memory::free(data);
- }
- auto allocate(unsigned size) -> void* {
- if(size == 0) return nullptr;
- if(size > Size) return memory::allocate(size);
- signed offset = list[cursor];
- if(offset < 0) return memory::allocate(size);
- list[cursor] = -1;
- cursor = (cursor + 1) % Count;
- return (void*)(data + offset * Size);
- }
- auto allocate(unsigned size, uint8_t data) -> void* {
- auto result = allocate(size);
- memset(result, data, size);
- return result;
- }
- auto resize(void* target, unsigned size) -> void* {
- if(target == nullptr) return allocate(size);
- signed offset = ((uint8_t*)target - data) / Size;
- if(offset < 0 || offset >= Count) return memory::resize(target, size);
- if(size <= Size) return target;
- cursor = (cursor - 1) % Count;
- list[cursor] = offset;
- return memory::allocate(size);
- }
- auto free(void* target) -> void {
- if(target == nullptr) return;
- signed offset = ((uint8_t*)target - data) / Size;
- if(offset < 0 || offset >= Count) return memory::free(target);
- cursor = (cursor - 1) % Count;
- list[cursor] = offset;
- }
- pool(const pool&) = delete;
- pool& operator=(const pool&) = delete;
- };
- }
- }
- auto nall::main(lstring args) -> void {
- memory::pool<65536, 256> pool;
- double r0;
- {
- clock_t a = clock();
- for(unsigned n = 0; n < 10000; n++) {
- for(unsigned l = 0; l < 4000; l++) {
- void* data = memory::allocate(128);
- *(uint8_t*)data = 0;
- data = memory::resize(data, 256);
- *(uint8_t*)data = 0;
- memory::free(data);
- }
- }
- clock_t b = clock();
- r0 = (double)(b - a);
- printf("%fs (malloc)\n", r0 / CLOCKS_PER_SEC);
- }
- double r1;
- {
- clock_t a = clock();
- for(unsigned n = 0; n < 10000; n++) {
- for(unsigned l = 0; l < 4000; l++) {
- void* data = pool.allocate(128);
- *(uint8_t*)data = 0;
- data = pool.resize(data, 256);
- *(uint8_t*)data = 0;
- pool.free(data);
- }
- }
- clock_t b = clock();
- r1 = (double)(b - a);
- printf("%fs (memory::pool)\n", r1 / CLOCKS_PER_SEC);
- }
- printf("delta: %fx\n", r0 / r1);
- printf("delta: %f%%\n", r1 / r0 * 100.0);
- }
- 16.562500s (malloc)
- 0.195312s (memory::pool)
- delta: 84.800000x
- delta: 1.179245%
Advertisement
Add Comment
Please, Sign In to add comment