Created
July 13, 2014 10:33
-
-
Save luikore/a1ec83827e6e897246fb to your computer and use it in GitHub Desktop.
pool alloc is about 2.5 times faster and smaller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
benchmark with gtime -f "%M" | |
pool alloc: | |
time: 0.028571 | |
22331392 | |
malloc: | |
time: 0.070064 | |
67125248 | |
*/ | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <stdbool.h> | |
#include <time.h> | |
#include <stdio.h> | |
#include <string.h> | |
#define SLOT_SIZE (4 * sizeof(void*)) | |
#define CHUNK_MAX 255 | |
struct SlotStruct; | |
typedef struct SlotStruct Slot; | |
struct SlotStruct { | |
Slot* next; | |
}; | |
struct ChunkStruct; | |
typedef struct ChunkStruct Chunk; | |
struct ChunkStruct { | |
uint64_t i; // 0...CHUNK_MAX | |
Chunk* next; | |
Slot data[CHUNK_MAX]; // 8k - 32 | |
}; | |
typedef struct { | |
Chunk* chunk_head; | |
Slot* slot_head; | |
} Pool; | |
static Pool pool = {NULL, NULL}; | |
static void _alloc_chunk() __attribute__((constructor(50))); | |
static void _alloc_chunk() { | |
Chunk* ch = malloc(sizeof(Chunk)); | |
ch->i = 0; | |
ch->next = pool.chunk_head; | |
pool.chunk_head = ch; | |
} | |
static bool _chunk_full(Chunk* ch) { | |
return (ch->i == CHUNK_MAX - 1); | |
} | |
void* pool_alloc() { | |
if (pool.slot_head) { | |
Slot* ret = pool.slot_head; | |
pool.slot_head = pool.slot_head->next; | |
return ret; | |
} | |
if (_chunk_full(pool.chunk_head)) { | |
_alloc_chunk(); | |
} | |
Chunk* ch = pool.chunk_head; | |
return (void*)(ch->data + ch->i++); | |
} | |
void pool_free(void* _p) { | |
Slot* p = _p; | |
p->next = pool.slot_head; | |
pool.slot_head = p; | |
} | |
int main (int argc, char const *argv[]) { | |
// clock_t t = clock(); | |
// for (long i = 0; i < 1000000; i++) { | |
// void* p = pool_alloc(); | |
// memset(p, 0, sizeof(void*) * 4); | |
// if (i % 2 == 0) { | |
// pool_free(p); | |
// } | |
// } | |
// printf("time: %f\n", ((double)(clock() - t))/CLOCKS_PER_SEC); | |
clock_t t = clock(); | |
for (long i = 0; i < 1000000; i++) { | |
void* p = malloc(4 * 8); | |
memset(p, 0, sizeof(void*) * 4); | |
if (i % 2 == 0) { | |
free(p); | |
} | |
} | |
printf("time: %f\n", ((double)(clock() - t))/CLOCKS_PER_SEC); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment