Add test5 to Makefile
[eleutheria.git] / buddy / test3.c
blobdccff6d9caf31a08deb0d3eeb76689c8851cf6c6
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_ERANGE) {
33 fprintf(stderr, "mpool: out of range in mpool_init()\n");
34 exit(EXIT_FAILURE);
36 else if (mpret == MPOOL_EBADVAL) {
37 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
38 exit(EXIT_FAILURE);
41 /* Initialize random number generator */
42 srand(time(NULL));
44 /* Allocate blocks */
45 for (i = 0; i < MAX_BLOCKS; i++) {
46 if ((pblk[i] = mpool_alloc(mpool, s = 1 << (5 + rand() % 7))) == NULL)
47 break;
50 * Zero out the allocated block
52 * By doing this, there is a chance that we catch
53 * allocator's bugs, i.e. by writing over the block
54 * and corrupting next block's header.
56 memset(pblk[i], 0, s);
58 /* Every now and then free a block to create holes and invoke merges */
59 if (rand() % 3 == 0) {
60 mpool_free(mpool, pblk[i]);
61 pblk[i] = NULL;
65 /* Free the rest of the blocks */
66 for (i = 0; i < MAX_BLOCKS; i++)
67 if (pblk[i] != NULL)
68 mpool_free(mpool, pblk[i]);
70 /* Dump statistics */
71 mpool_stat_get_nodes(mpool, &an, &un);
72 mpool_stat_get_bytes(mpool, &ab, &ub);
73 me = mpool_stat_get_merges(mpool);
74 sp = mpool_stat_get_splits(mpool);
76 printf("avail nodes = %-5u\tused nodes = %-5u\tfree(%%) = %.2f\n",
77 an, un, 100.0 * an / (an + un));
78 printf("avail bytes = %-5u\tused bytes = %-5u\tfree(%%) = %.2f\n",
79 ab, ub, 100.0 * ab / (ab + ub));
80 printf("splits = %-5u\tmerges = %-5u\n",
81 sp, me);
83 /* Destroy memory pool and free all resources */
84 mpool_destroy(mpool);
86 return EXIT_SUCCESS;