Name: Anonymous 2012-11-06 15:22
Hello people.
I made an allocation system.
It must be initialized and can only allocate a fixed-number of same-sized memory blocks (of at least sizeof(void*) bytes).
It allows freeing memory blocs, which can be reused later.
(it also displays how ugly pointer syntax can be)
I made a small benchmark to allocate and free 10000 times 10000 blocks of 1024 bytes. caralloc and carafree are more than 51 times faster than malloc and free here.
What do you guys think ?
I made an allocation system.
It must be initialized and can only allocate a fixed-number of same-sized memory blocks (of at least sizeof(void*) bytes).
It allows freeing memory blocs, which can be reused later.
(it also displays how ugly pointer syntax can be)
I made a small benchmark to allocate and free 10000 times 10000 blocks of 1024 bytes. caralloc and carafree are more than 51 times faster than malloc and free here.
#define PTRSIZE sizeof(void*)
char* caralloc_main_pointer;
char* caralloc_memory;
void init_caralloc(size_t cell_size, unsigned int cells)
{
int i;
if(cell_size < PTRSIZE)
fprintf(stderr, "caralloc error: cell_size is of %zd, it should be at least %ld\n", cell_size, PTRSIZE);
else
{
caralloc_memory = calloc(cells, cell_size);
for(i = 0; i < cells-1; i++)
*((void**)(((char*)caralloc_memory) + i*cell_size)) = ((void*)caralloc_memory) + (i+1) * cell_size;
*((void**)(((char*)caralloc_memory) + (cells-1) * cell_size)) = NULL;
caralloc_main_pointer = caralloc_memory;
}
}
void quit_caralloc()
{
free(caralloc_memory);
}
void* caralloc()
{
void** main_pointer = (void**) caralloc_main_pointer;
caralloc_main_pointer = *main_pointer;
return (void*) main_pointer;
}
void carafree(void* ptr)
{
memcpy(caralloc_main_pointer, ptr, PTRSIZE);
caralloc_main_pointer = ptr;
}
#define N 10000
#define K 10000
#define S 1024
int main()
{
void* ptrs[N];
long clocks[2];
clock_t start, end;
int i, j;
size_t size = S;
init_caralloc(size, N+1);
start = clock();
for(j = 0; j < K; j++)
{
for(i = 0; i < N; i++) ptrs[i] = malloc(size);
for(i = 0; i < N; i++) free(ptrs[i]);
}
end = clock();
clocks[0] = end-start;
printf(" malloc & free : %ld clocks\n", clocks[0]);
start = clock();
for(j = 0; j < K; j++)
{
for(i = 0; i < N; i++) ptrs[i] = caralloc();
for(i = 0; i < N; i++) carafree(ptrs[i]);
}
end = clock();
clocks[1] = end-start;
printf("caralloc & carafree: %ld clocks\n", clocks[1]);
printf("caralloc is %f times faster than malloc\n", ((double)clocks[0]) / ((double)clocks[1]));
quit_caralloc();
}What do you guys think ?