Honour 80 cols per line limit
[eleutheria.git] / buddy / test3.c
blobdb619037ceaaef8337e3891ab2d749bebd5dbae1
1 /*
2 * Compile with:
3 * gcc test3.c mpool.c mstat.c -o test3 -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h> /* for memset() */
9 #include <time.h> /* for time() in srand() */
11 #include "mpool.h"
12 #include "mstat.h"
14 #define MAX_BLOCKS 1000
16 int main(void)
18 char *pblk[MAX_BLOCKS];
19 mpool_t *mpool;
20 mpret_t mpret;
21 size_t an, un; /* nodes */
22 size_t ab, ub; /* blocks */
23 size_t me, sp; /* merges, splits */
24 size_t i, s;
26 /* Initialize memory pool with 1048576 bytes */
27 mpret = mpool_init(&mpool, 20, 5);
28 if (mpret == MPOOL_ENOMEM) {
29 fprintf(stderr, "mpool: not enough memory\n");
30 exit(EXIT_FAILURE);
32 else if (mpret == MPOOL_EBADVAL) {
33 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
34 exit(EXIT_FAILURE);
37 /* Initialize random number generator */
38 srand(time(NULL));
40 /* Allocate blocks */
41 for (i = 0; i < MAX_BLOCKS; i++) {
42 if ((pblk[i] = mpool_alloc(mpool, s = 1 << (5 + rand() % 7))) == NULL)
43 break;
46 * Zero out the allocated block
48 * By doing this, there is a chance that we catch
49 * allocator's bugs, i.e. by writing over the block
50 * and corrupting next block's header.
52 memset(pblk[i], 0, s);
54 /* Every now and then free a block to create holes and invoke merges */
55 if (rand() % 3 == 0) {
56 mpool_free(mpool, pblk[i]);
57 pblk[i] = NULL;
61 /* Free the rest of the blocks */
62 for (i = 0; i < MAX_BLOCKS; i++)
63 if (pblk[i] != NULL)
64 mpool_free(mpool, pblk[i]);
66 /* Dump statistics */
67 mpool_stat_get_nodes(mpool, &an, &un);
68 mpool_stat_get_bytes(mpool, &ab, &ub);
69 me = mpool_stat_get_merges(mpool);
70 sp = mpool_stat_get_splits(mpool);
72 printf("avail nodes = %-5u\tused nodes = %-5u\tfree(%%) = %.2f\n",
73 an, un, 100.0 * an / (an + un));
74 printf("avail bytes = %-5u\tused bytes = %-5u\tfree(%%) = %.2f\n",
75 ab, ub, 100.0 * ab / (ab + ub));
76 printf("splits = %-5u\tmerges = %-5u\n",
77 sp, me);
79 /* Destroy memory pool and free all resources */
80 mpool_destroy(mpool);
82 return EXIT_SUCCESS;