summaryrefslogtreecommitdiff
path: root/ccan/avl/test/run.c
blob: f621a327aa80075229e6b76838ea810617253132 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*
 * Copyright (C) 2010 Joseph Adams <joeyadams3.14159@gmail.com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <ccan/avl/avl.h>

#define remove remove_
#include <ccan/avl/avl.c>
#undef remove

#include <ccan/tap/tap.h>

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ANIMATE_RANDOM_ACCESS 0

#if ANIMATE_RANDOM_ACCESS

#include <sys/time.h>

typedef int64_t msec_t;

static msec_t time_ms(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#endif

uint32_t rand32_state = 0;

/*
 * Finds a pseudorandom 32-bit number from 0 to 2^32-1 .
 * Uses the BCPL linear congruential generator method.
 *
 * Note: this method (or maybe just this implementation) seems to
 *       go back and forth between odd and even exactly, which can
 *       affect low-cardinality testing if the cardinality given is even.
 */
static uint32_t rand32(void)
{
	rand32_state *= (uint32_t)0x7FF8A3ED;
	rand32_state += (uint32_t)0x2AA01D31;
	return rand32_state;
}

static void scramble(void *base, size_t nmemb, size_t size)
{
	char *i = base;
	char *o;
	size_t sd;
	for (;nmemb>1;nmemb--) {
		o = i + size*(rand32()%nmemb);
		for (sd=size;sd--;) {
			char tmp = *o;
			*o++ = *i;
			*i++ = tmp;
		}
	}
}

static struct {
	size_t success;
	size_t passed_invariants_checks;
	
	size_t excess;
	size_t duplicate;
	size_t missing;
	size_t incorrect;
	size_t failed;
	size_t failed_invariants_checks;
} stats;

static void clear_stats(void)
{
	memset(&stats, 0, sizeof(stats));
}

static bool print_stats(const char *success_label, size_t expected_success)
{
	int failed = 0;
	
	printf("      %s:  \t%zu\n", success_label, stats.success);
	if (stats.success != expected_success)
		failed = 1;
	
	if (stats.passed_invariants_checks)
		printf("      Passed invariants checks: %zu\n", stats.passed_invariants_checks);
	
	if (stats.excess)
		failed = 1, printf("      Excess:     \t%zu\n", stats.excess);
	if (stats.duplicate)
		failed = 1, printf("      Duplicate:  \t%zu\n", stats.duplicate);
	if (stats.missing)
		failed = 1, printf("      Missing:    \t%zu\n", stats.missing);
	if (stats.incorrect)
		failed = 1, printf("      Incorrect:  \t%zu\n", stats.incorrect);
	if (stats.failed)
		failed = 1, printf("      Failed:     \t%zu\n", stats.failed);
	if (stats.failed_invariants_checks)
		failed = 1, printf("      Failed invariants checks: %zu\n", stats.failed_invariants_checks);
	
	return !failed;
}

struct test_item {
	uint32_t key;
	uint32_t value;
	size_t   insert_id; /* needed because qsort is not a stable sort */
};

static int compare_test_item(const void *ap, const void *bp)
{
	const struct test_item *a = *(void**)ap, *b = *(void**)bp;
	
	if (a->key < b->key)
		return -1;
	if (a->key > b->key)
		return 1;
	
	if (a->insert_id < b->insert_id)
		return -1;
	if (a->insert_id > b->insert_id)
		return 1;
	
	return 0;
}

static bool test_insert_item(AVL *avl, struct test_item *item)
{
	avl_insert(avl, &item->key, &item->value);
	return true;
}

static bool test_lookup_item(const AVL *avl, const struct test_item *item)
{
	return avl_member(avl, &item->key) && avl_lookup(avl, &item->key) == &item->value;
}

static bool test_remove_item(AVL *avl, struct test_item *item)
{
	return avl_remove(avl, &item->key);
}

static void test_foreach(AVL *avl, struct test_item **test_items, int count)
{
	AvlIter iter;
	int     i;
	
	i = 0;
	avl_foreach(iter, avl) {
		if (i >= count) {
			stats.excess++;
			continue;
		}
		if (iter.key == &test_items[i]->key && iter.value == &test_items[i]->value)
			stats.success++;
		else
			stats.incorrect++;
		i++;
	}
}

static void test_foreach_reverse(AVL *avl, struct test_item **test_items, int count)
{
	AvlIter iter;
	int     i;
	
	i = count - 1;
	avl_foreach_reverse(iter, avl) {
		if (i < 0) {
			stats.excess++;
			continue;
		}
		if (iter.key == &test_items[i]->key && iter.value == &test_items[i]->value)
			stats.success++;
		else
			stats.incorrect++;
		i--;
	}
}

static void benchmark(size_t max_per_trial, size_t round_count, bool random_counts, int cardinality)
{
	struct test_item **test_item;
	struct test_item *test_item_array;
	size_t i, o, count;
	size_t round = 0;
	
	test_item = malloc(max_per_trial * sizeof(*test_item));
	test_item_array = malloc(max_per_trial * sizeof(*test_item_array));
	
	if (!test_item || !test_item_array) {
		fail("Not enough memory for %zu keys per trial\n",
			max_per_trial);
		return;
	}
	
	/* Initialize test_item pointers. */
	for (i=0; i<max_per_trial; i++)
		test_item[i] = &test_item_array[i];
	
	/*
	 * If round_count is not zero, run round_count trials.
	 * Otherwise, run forever.
	 */
	for (round = 1; round_count==0 || round <= round_count; round++) {
		AVL *avl;
		
		if (cardinality)
			printf("Round %zu (cardinality = %d)\n", round, cardinality);
		else
			printf("Round %zu\n", round);
		
		if (random_counts)
			count = rand32() % (max_per_trial+1);
		else
			count = max_per_trial;
		
		/*
		 * Initialize test items by giving them sequential keys and
		 * random values. Scramble them so the order of insertion
		 * will be random.
		 */
		for (i=0; i<count; i++) {
			test_item[i]->key   = rand32();
			test_item[i]->value = rand32();
			
			if (cardinality)
				test_item[i]->key %= cardinality;
		}
		scramble(test_item, count, sizeof(*test_item));
		
		avl = avl_new(order_u32_noctx);
		
		clear_stats();
		printf("   Inserting %zu items...\n", count);
		for (i=0; i<count; i++) {
			if (test_insert_item(avl, test_item[i])) {
				stats.success++;
				test_item[i]->insert_id = i;
			} else {
				printf("invariants check failed at insertion %zu\n", i);
				stats.failed++;
			}
			
			/* Periodically do an invariants check */
			if (count / 10 > 0 && i % (count / 10) == 0) {
				if (avl_check_invariants(avl))
					stats.passed_invariants_checks++;
				else
					stats.failed_invariants_checks++;
			}
		}
		ok1(print_stats("Inserted", count));
		ok1(avl_check_invariants(avl));
		
		/* remove early duplicates, as they are shadowed in insertions. */
		qsort(test_item, count, sizeof(*test_item), compare_test_item);
		for (i = 0, o = 0; i < count;) {
			uint32_t k = test_item[i]->key;
			do i++; while (i < count && test_item[i]->key == k);
			test_item[o++] = test_item[i-1];
		}
		count = o;
		ok1(avl_count(avl) == count);
		
		scramble(test_item, count, sizeof(*test_item));
		
		printf("   Finding %zu items...\n", count);
		clear_stats();
		for (i=0; i<count; i++) {
			if (!test_lookup_item(avl, test_item[i]))
				stats.missing++;
			else
				stats.success++;
		}
		ok1(print_stats("Retrieved", count));
		
		qsort(test_item, count, sizeof(*test_item), compare_test_item);
		
		printf("   Traversing forward through %zu items...\n", count);
		clear_stats();
		test_foreach(avl, test_item, count);
		ok1(print_stats("Traversed", count));
		
		printf("   Traversing backward through %zu items...\n", count);
		clear_stats();
		test_foreach_reverse(avl, test_item, count);
		ok1(print_stats("Traversed", count));
		
		scramble(test_item, count, sizeof(*test_item));
		
		printf("   Deleting %zu items...\n", count);
		clear_stats();
		for (i=0; i<count; i++) {
			if (test_remove_item(avl, test_item[i]))
				stats.success++;
			else
				stats.missing++;
			
			/* Periodically do an invariants check */
			if (count / 10 > 0 && i % (count / 10) == 0) {
				if (avl_check_invariants(avl))
					stats.passed_invariants_checks++;
				else
					stats.failed_invariants_checks++;
			}
		}
		ok1(print_stats("Deleted", count));
		ok1(avl_count(avl) == 0);
		ok1(avl_check_invariants(avl));
		
		avl_free(avl);
	}
	
	free(test_item);
	free(test_item_array);
}

static int compare_ptr(const void *a, const void *b)
{
	if (a < b)
		return -1;
	if (a > b)
		return 1;
	return 0;
}

struct fail_total {
	int64_t fail;
	int64_t total;
};

static bool print_pass_fail(struct fail_total *pf, const char *label)
{
	long long fail  = pf->fail,
	          total = pf->total;
	
	printf("%s:\t%lld / %lld\n", label, total - fail, total);
	
	return fail == 0;
}

static void test_random_access(uint32_t max, int64_t ops)
{
	char       *in_tree;
	AVL        *avl;
	int64_t     i;
	struct {
		struct fail_total
			inserts, lookups, removes, checks;
	} s;
	
	#if ANIMATE_RANDOM_ACCESS
	msec_t last_update, now;
	msec_t interval = 100;
	#endif
	
	memset(&s, 0, sizeof(s));
	
	in_tree = malloc(max);
	memset(in_tree, 0, max);
	
	avl = avl_new(compare_ptr);
	
	#if ANIMATE_RANDOM_ACCESS
	now = time_ms();
	last_update = now - interval;
	#endif
	
	for (i = 0; i < ops; i++) {
		char *item = &in_tree[rand32() % max];
		char *found;
		bool  inserted, removed;
		
		#if ANIMATE_RANDOM_ACCESS
		now = time_ms();
		if (now >= last_update + interval) {
			last_update = now;
			printf("\r%.2f%%\t%zu / %zu\033[K", (double)i * 100 / ops, avl_count(avl), max);
			fflush(stdout);
		}
		#endif
		
		switch (rand32() % 3) {
			case 0:
				inserted = avl_insert(avl, item, item);
				
				if ((*item == 0 && !inserted) ||
				    (*item == 1 && inserted))
					s.inserts.fail++;
				
				if (inserted)
					*item = 1;
				
				s.inserts.total++;
				break;
			
			case 1:
				found = avl_lookup(avl, item);
				
				if ((*item == 0 && found != NULL) ||
				    (*item == 1 && found != item) ||
				    (avl_member(avl, item) != !!found))
					s.lookups.fail++;
				
				s.lookups.total++;
				break;
			
			case 2:
				removed = avl_remove(avl, item);
				
				if ((*item == 0 && removed) ||
				    (*item == 1 && !removed))
					s.removes.fail++;
				
				if (removed)
					*item = 0;
				
				s.removes.total++;
				break;
		}
		
		/* Periodically do an invariants check */
		if (ops / 10 > 0 && i % (ops / 10) == 0) {
			if (!avl_check_invariants(avl))
				s.checks.fail++;
			s.checks.total++;
		}
	}
	
	#if ANIMATE_RANDOM_ACCESS
	printf("\r\033[K");
	#endif
	
	avl_free(avl);
	free(in_tree);
	
	ok1(print_pass_fail(&s.inserts, "Inserts"));
	ok1(print_pass_fail(&s.lookups, "Lookups"));
	ok1(print_pass_fail(&s.removes, "Removes"));
	ok1(print_pass_fail(&s.checks,  "Invariants checks"));
}

int main(void)
{
	plan_tests(18 * 3 + 4);
	
	benchmark(100000, 2, false, 0);
	benchmark(100000, 2, false, 12345);
	benchmark(100000, 2, false, 100001);
	
	printf("Running random access test\n");
	test_random_access(12345, 1234567);
	
	return exit_status();
}