diff options
Diffstat (limited to 'bench.c')
-rw-r--r-- | bench.c | 72 |
1 files changed, 72 insertions, 0 deletions
@@ -0,0 +1,72 @@ +#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 10 +#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)); + } + printf(" %*zu\n", SIZE_WIDTH, size); + } + puts(""); + } + + return 0; +} + |