// test block allocation // #include #include void *emalloc( size_t nbytes) { // malloc() with exit on error void *p = malloc(nbytes); if(!p) { fprintf( stderr, "malloc() failed\n"); exit(1); } return p; } typedef struct node { double x; int y; /* ... data ... */ struct node *next; } Node; #if BLOCK static Node *head = 0; static int block = 1000; // number of nodes to allocate at one time Node *new_node( void) { if( !head) { // allocate a block of nodes head = emalloc(block*sizeof(Node)); Node *last = head+block-1; for( Node *p = head; p < last; ++p) p->next = p+1; // link the nodes last->next = 0; } Node *n = head; head = head->next; return n; // return head of list } void free_node( Node *n) { n->next = head; head = n; // insert at head of list } #else #define new_node() emalloc(sizeof(Node)) #define free_node(n) free(n) #endif int main( void) { Node *h = 0; // for linked list int N = 1000000, loop = 50; for( int i = 0; i < loop; ++i) { for( int j = 0; j < N; ++j) { Node *x = new_node(); // x->next = x; // free_node(x); x->next = h; h = x; // save in linked-list } } #if FREE for( int i = 0; i < loop; ++i) // free the list { for( int j = 0; j < N; ++j) { Node *x = h; h = x->next; free_node(x); } } #endif } /* sample runs: $ make gcc -O2 -Wall block.c gcc -O2 -Wall -DBLOCK=1 -o block block.c gcc -O2 -Wall -DFREE=1 -o a.out+free block.c gcc -O2 -Wall -DFREE=1 -DBLOCK=1 -o block+free block.c $ time ./a.out real 0m1.825s user 0m1.198s sys 0m0.623s $ time ./block real 0m0.745s user 0m0.291s sys 0m0.452s $ time ./a.out+free real 0m2.409s user 0m1.783s sys 0m0.622s $ time ./block+free real 0m0.968s user 0m0.481s sys 0m0.483s $ */