summaryrefslogtreecommitdiff
path: root/bench.c
blob: 75bf32e03f1076357e05a774a4050ae592853452 (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
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "testcases.h"
#include "sorters.h"

#define CMP_WIDTH  12
#define MS_WIDTH   6
#define SORT_WIDTH 16
#define TEST_WIDTH (CMP_WIDTH + MS_WIDTH + 1)
#define SIZE_WIDTH 10

static inline unsigned long timediff_ms(struct timespec *start, struct timespec *stop)
{
	return 1000 * (stop->tv_sec - start->tv_sec) + (stop->tv_nsec - start->tv_nsec) / 1000000;
}

int main()
{
	struct timespec start, stop;

	printf("%-*s ", SORT_WIDTH, "");
	for (const struct testcase *t = testcases; t->name; t++)
		printf("%*s ", TEST_WIDTH, t->name);
	printf(" %*s\n%-*s ", SIZE_WIDTH, "elements", SORT_WIDTH, "");
	for (const struct testcase *t = testcases; t->name; t++)
		printf("%*s %*s ", CMP_WIDTH, "compares", MS_WIDTH, "ms");
	puts("");

	for (const struct sorter *s = sorters; s->name; s++) {
		for (size_t size = MIN_SIZE; size <= MAX_SIZE; size *= 10) {
			printf("%-*s ", SORT_WIDTH, size == MIN_SIZE ? s->name : "");
			for (const struct testcase *t = testcases; t->name; t++) {
				comparisons = 0;
				t->init(size);

				if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &start)) abort();
				s->func(buffer, size, sizeof(int), t->cmp);
				if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &stop)) abort();

				printf("%*lu %*lu ", CMP_WIDTH, comparisons, MS_WIDTH, timediff_ms(&start, &stop));
				assert_sorted(size, t->cmp);
			}
			printf(" %*zu\n", SIZE_WIDTH, size);
		}
		puts("");
	}

	return 0;
}