Create benchmarking library
This commit is contained in:
85
benchmarks/benchmarking.c
Normal file
85
benchmarks/benchmarking.c
Normal file
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright (c) Camden Dixie O'Brien
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
#include "benchmarking.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define SWAP(x, y) \
|
||||
do { \
|
||||
const double tmp = x; \
|
||||
x = y; \
|
||||
y = tmp; \
|
||||
} while (0)
|
||||
|
||||
clock_t benchmark_start, benchmark_end;
|
||||
|
||||
static void sort(double *xs, int n)
|
||||
{
|
||||
if (n <= 0)
|
||||
return;
|
||||
|
||||
const double pivot = xs[(n - 1) / 2];
|
||||
int lt = 0;
|
||||
int eq = 0;
|
||||
int gt = n - 1;
|
||||
while (eq <= gt) {
|
||||
if (xs[eq] < pivot) {
|
||||
SWAP(xs[eq], xs[lt]);
|
||||
++lt;
|
||||
++eq;
|
||||
} else if (xs[eq] > pivot) {
|
||||
SWAP(xs[eq], xs[gt]);
|
||||
--gt;
|
||||
} else {
|
||||
++eq;
|
||||
}
|
||||
}
|
||||
|
||||
sort(xs, lt);
|
||||
sort(xs + gt + 1, n - (gt + 1));
|
||||
}
|
||||
|
||||
void benchmark_summarise(double *res, int reps, benchmark_summary_t *out)
|
||||
{
|
||||
assert(reps > 0);
|
||||
|
||||
sort(res, reps);
|
||||
const double median = res[reps / 2];
|
||||
|
||||
double sum = 0;
|
||||
for (int i = 0; i < reps; ++i)
|
||||
sum += res[i];
|
||||
const double mean = sum / reps;
|
||||
|
||||
double diff_sum = 0;
|
||||
for (int i = 0; i < reps; ++i)
|
||||
diff_sum += pow(res[i] - mean, 2);
|
||||
const double variance = diff_sum / (reps - 1);
|
||||
|
||||
out->reps = reps;
|
||||
out->total = sum;
|
||||
out->median = median;
|
||||
out->mean = mean;
|
||||
out->min = res[0];
|
||||
out->max = res[reps - 1];
|
||||
out->stddev = sqrt(variance);
|
||||
}
|
||||
|
||||
void benchmark_print_header(void)
|
||||
{
|
||||
printf(
|
||||
"%-12s %13s %13s %13s %13s %12s\n", "benchmark", "median (µs)",
|
||||
"mean (µs)", "min (µs)", "max (µs)", "stddev");
|
||||
}
|
||||
|
||||
void benchmark_print(const char *name, const benchmark_summary_t *s)
|
||||
{
|
||||
printf(
|
||||
"%-12s %12.2f %12.2f %12.2f %12.2f %12.2f\n", name, s->median,
|
||||
s->mean, s->min, s->max, s->stddev);
|
||||
}
|
||||
Reference in New Issue
Block a user