test_malo.c revision fb3e20e0
1/* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc. See LICENSE. */ 2#include <assert.h> 3#include <stdint.h> 4#include <stdio.h> 5#include <stdlib.h> 6#ifndef WIN32 7#include <unistd.h> 8#else 9#include "getopt.h" 10#endif 11 12#include "lsquic_malo.h" 13 14struct elem { 15 unsigned id; 16}; 17 18 19#define N_ELEMS 10000 /* More and it hits swap on smaller VMs */ 20 21static void 22run_tests (size_t el_size) 23{ 24 unsigned i; 25 struct malo *malo; 26 struct elem *el; 27 28 malo = lsquic_malo_create(el_size); 29 assert(malo); 30 31 for (i = 1; i <= N_ELEMS; ++i) 32 { 33 el = lsquic_malo_get(malo); 34 el->id = i; 35 } 36 37 uint64_t sum = 0, deleted_sum = 0; 38 for (el = lsquic_malo_first(malo); el; el = lsquic_malo_next(malo)) 39 { 40 sum += el->id; 41 if (el->id % 3 == 0) /* Delete every third element */ 42 { 43 deleted_sum += el->id; 44 lsquic_malo_put(el); 45 } 46 } 47 48 assert(sum == ((uint64_t) N_ELEMS + 1) * ((uint64_t) N_ELEMS / 2)); 49 50 sum = 0; 51 for (el = lsquic_malo_first(malo); el; el = lsquic_malo_next(malo)) 52 { 53 sum += el->id; 54 lsquic_malo_put(el); 55 } 56 57 assert(sum == ((uint64_t) N_ELEMS + 1) * ((uint64_t) N_ELEMS / 2) - 58 deleted_sum); 59 60 el = lsquic_malo_first(malo); 61 assert(!el); 62 63 lsquic_malo_destroy(malo); 64} 65 66 67static struct elem *elems[10000]; 68 69static void 70alloc_using_malloc (int n) 71{ 72 int i; 73 for (i = 0; i < n; ++i) 74 { 75 unsigned j; 76 for (j = 0; j < sizeof(elems) / sizeof(elems[0]); ++j) 77 { 78 elems[j] = malloc(sizeof(*elems[j])); 79 elems[j]->id = j; 80 } 81 for (j = 0; j < sizeof(elems) / sizeof(elems[0]); ++j) 82 { 83 free(elems[j]); 84 } 85 } 86} 87 88 89static void 90alloc_using_malo (int n) 91{ 92 struct malo *malo = lsquic_malo_create(sizeof(struct elem)); 93 int i; 94 for (i = 0; i < n; ++i) 95 { 96 unsigned j; 97 for (j = 0; j < sizeof(elems) / sizeof(elems[0]); ++j) 98 { 99 elems[j] = lsquic_malo_get(malo); 100 elems[j]->id = j; 101 } 102 for (j = 0; j < sizeof(elems) / sizeof(elems[0]); ++j) 103 { 104 lsquic_malo_put(elems[j]); 105 } 106 } 107 lsquic_malo_destroy(malo); 108} 109 110 111int 112main (int argc, char **argv) 113{ 114 int opt, mode = -1, n = 1; 115 while (-1 != (opt = getopt(argc, argv, "s:n:"))) 116 { 117 switch (opt) 118 { 119 case 's': 120 mode = atoi(optarg); 121 break; 122 case 'n': 123 n = atoi(optarg); 124 break; 125 default: 126 exit(1); 127 } 128 } 129 130 switch (mode) 131 { 132 case -1: 133 { 134 size_t sz; 135 for (sz = sizeof(struct elem); sz < 0x800; sz <<= 1) 136 { 137 run_tests(sz - 3); 138 run_tests(sz - 1); 139 run_tests(sz); 140 run_tests(sz + 1); 141 run_tests(sz + 3); 142 } 143 break; 144 } 145 case 0: 146 alloc_using_malloc(n); 147 break; 148 case 1: 149 alloc_using_malo(n); 150 break; 151 default: 152 fprintf(stderr, "error: invalid mode %d\n", mode); 153 exit(2); 154 } 155 156 return 0; 157} 158