Last active
August 22, 2016 03:39
-
-
Save cloudwu/0771fa6627d11a221f066440b79a880e to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <assert.h> | |
struct memnode { | |
struct memnode * next; | |
}; | |
struct fixalloc { | |
struct memnode *freelist; | |
int nodesz; | |
int cap; | |
int used; | |
int freed; | |
}; | |
struct fixalloc * | |
fixalloc_create(int nodesz, int cap) { | |
struct fixalloc * pool = malloc(sizeof(*pool)); | |
pool->freelist = NULL; | |
pool->nodesz = nodesz; | |
pool->used = 0; | |
pool->freed = 0; | |
pool->cap = cap; | |
return pool; | |
} | |
void | |
fixalloc_release(struct fixalloc *pool) { | |
free(pool); | |
} | |
void * | |
fixalloc_alloc(struct fixalloc *pool) { | |
pool->used++; | |
if (pool->freelist) { | |
struct memnode * ret = pool->freelist; | |
pool->freelist = ret->next; | |
return ret; | |
} | |
return malloc(pool->nodesz); | |
} | |
void | |
fixalloc_free(struct fixalloc *pool, void *p) { | |
assert(p != NULL); | |
assert(pool->used > 0); | |
struct memnode *n = p; | |
--pool->used; | |
++pool->freed; | |
n->next = pool->freelist; | |
pool->freelist = n; | |
} | |
void | |
fixalloc_collect(struct fixalloc *pool, int ti) { | |
int total = pool->used + pool->freed; | |
int n = total - pool->cap; | |
if (n > pool->freed) | |
n = pool->freed; | |
if (n <= 0) | |
return; | |
clock_t ct = clock(); | |
int i; | |
for (i=0;i<n;i++) { | |
struct memnode * p = pool->freelist; | |
pool->freelist = p->next; | |
free(p); | |
clock_t t = clock() - ct; | |
if (t * 1000 / CLOCKS_PER_SEC > ti) | |
break; | |
} | |
pool->freed -= i; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment