Skip to content

Instantly share code, notes, and snippets.

@tkhoa2711
Last active October 4, 2015 15:46
Show Gist options
  • Save tkhoa2711/1adc1e7602e1d193ea30 to your computer and use it in GitHub Desktop.
Save tkhoa2711/1adc1e7602e1d193ea30 to your computer and use it in GitHub Desktop.
A minimal memory pool allocator
#include <stdio.h>
#include <time.h>
#include "pool.h"
int main()
{
#ifdef TEST_USE_POOL
printf("test use pool\n");
#else
printf("test without pool\n");
#endif
pool_t * p;
p = pool_create(512);
clock_t begin, end;
begin = clock();
int i, *m;
for (i = 0; i < 100000000; i++)
{
#ifdef TEST_USE_POOL
m = pool_alloc(p, sizeof(int));
#else
m = (int*) malloc(sizeof(int));
#endif
}
pool_free(p);
end = clock();
double duration = (double)(end - begin)/CLOCKS_PER_SEC;
printf("time: %f\n", duration);
return 0;
}
CFLAGS=-g -O2 -W -Wall
TEST_USE_POOL=-DTEST_USE_POOL
OBJS=main.o pool.o
DEPS=pool.h
TARGETS=test_pool test_no_pool
TEMPS=main_pool.c
.PHONY : all clean test
all: $(TARGETS)
test_no_pool: main.o pool.o
$(CC) -lrt $^ -o $@
test_pool: CFLAGS += -DTEST_USE_POOL
test_pool: main_pool.o pool.o
$(CC) -lrt $^ -o $@
%.o : %.c $(DEPS)
$(CC) $(CFLAGS) -c $^
main_pool.o: main.c pool.h
cp main.c main_pool.c
$(CC) $(CFLAGS) -c main_pool.c pool.h
$(RM) main_pool.c
test: all
./test_pool
./test_no_pool
clean:
$(RM) $(TARGETS) $(TEMPS) *.o *.gch
#include "pool.h"
pool_t * pool_create(size_t size)
{
pool_t * p = (pool_t*) malloc(size + sizeof(pool_t));
p->next = (char*) &p[1];
p->end = p->next + size;
return p;
}
void * pool_alloc(pool_t * p, size_t size)
{
if (pool_available(p) < size) return NULL;
void * mem = (void*) p->next;
p->next += size;
return mem;
}
size_t pool_available(pool_t * p)
{
return p->end - p->next;
}
void pool_free(pool_t * p)
{
free(p);
}
#ifndef _POOL_H_
#define _POOL_H_
#include <stdlib.h>
typedef struct pool_t
{
char * next;
char * end;
} pool_t;
/* Create a pool with a given initial size
*/
pool_t * pool_create(size_t size);
/* Allocate memory for the give size.
* Return a pointer the first free byte.
*/
void * pool_alloc(pool_t * pool, size_t size);
/* Check how much memory remaining this pool has.
*/
size_t pool_available(pool_t * pool);
/* Delete the pool.
*/
void pool_free(pool_t * pool);
#endif // _POOL_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment