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

#include "testcases.h"
#include "sorters.h"
#include "common.h"
#include "counts.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;

	setvbuf(stdout, NULL, _IONBF, 0);

	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++) {
				clear_all_counts();
				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, counts[CURRENT].compare, MS_WIDTH, timediff_ms(&start, &stop));
				print_counts();
				assert_sorted((void*)buffer, size, sizeof(int), t->cmp);
			}
			printf(" %*zu\n", SIZE_WIDTH, size);
		}
		puts("");
	}

	return 0;
}