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

#include "generators.h"
#include "sorters.h"

#define MIN_SIZE 10000
#define MAX_SIZE 10000000

static int buffer[MAX_SIZE];
static unsigned long comparisons;

static int compare(const void *a, const void *b)
{
	const int *aa = a;
	const int *bb = b;

	comparisons++;
	if (*aa < *bb)
		return -1;
	else if (*aa > *bb)
		return 1;
	else
		return 0;
}

#define CMP_WIDTH  12
#define MS_WIDTH   6
#define SORT_WIDTH 16
#define GEN_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 generator *g = generators; g->name; g++)
		printf("%*s ", GEN_WIDTH, g->name);
	printf(" %*s\n%-*s ", SIZE_WIDTH, "elements", SORT_WIDTH, "");
	for (const struct generator *g = generators; g->name; g++)
		printf("%*s %*s ", CMP_WIDTH, "compares", MS_WIDTH, "ms");
	puts("");

	for (const struct sorter *s = sorters; s->name; s++) {
		for (size_t size = MAX_SIZE; size >= MIN_SIZE; size /= 10) {
			printf("%-*s ", SORT_WIDTH, size == MAX_SIZE ? s->name : "");
			for (const struct generator *g = generators; g->name; g++) {
				comparisons = 0;
				g->func(buffer, size);

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

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

	return 0;
}