about summary refs log tree commit diff stats
path: root/bench.c
blob: fb95c2e00d0d65edae90559964c8045e44e3210b (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

#include "cached.h"

#define UNUSED __attribute__((unused))

static sig_atomic_t running;

static void
panic(const char *msg)
{
	fprintf(stderr, "panic: %s\n", msg);
	exit(EXIT_FAILURE);
}

static void
alarm_handler(int sig UNUSED, siginfo_t *info UNUSED, void *arg UNUSED)
{
	running = 0;
}

static void
trap_signals(void)
{
	struct sigaction sa;

	sa.sa_sigaction = alarm_handler;
	sa.sa_flags = SA_SIGINFO;

	if (sigaction(SIGALRM, &sa, NULL) < 0) {
		panic("failed to setup signal handler");
	}
}

static void
set_alarm(void)
{
	running = 1;
	alarm(1);
}

static size_t
bench_malloc(size_t allocs, size_t objsize)
{
	void *objs[allocs];
	size_t count = 0;

	while (running) {
		for (size_t i = 0; i < allocs; i++) {
			objs[i] = calloc(1, objsize);
			count++;
		}
		for (size_t i = 0; i < allocs; i++) {
			free(objs[i]);
		}
	}

	return count;
}

static size_t
bench_ca_alloc(size_t allocs)
{
	void *objs[allocs];
	size_t count = 0;

	while (running) {
		for (size_t i = 0; i < allocs; i++) {
			objs[i] = ca_alloc();
			count++;
		}
		for (size_t i = 0; i < allocs; i++) {
			ca_free(objs[i]);
		}
	}

	return count;
}

static void
bench_four(void)
{
	if (ca_setup(256, 4096) < 0) {
		panic("failed to setup cached allocator");
	}

	set_alarm();

	size_t allocs = bench_ca_alloc(1024);

	printf("%-12s\t%9zu allocs/second\n", "huge_cache", allocs);

	ca_cleanup();
}

static void
bench_one(void)
{
	if (ca_setup(256, 1024) < 0) {
		panic("failed to setup cached allocator");
	}

	set_alarm();

	size_t allocs = bench_ca_alloc(1024);

	printf("%-12s\t%9zu allocs/second\n", "large_cache", allocs);

	ca_cleanup();
}

static void
bench_two(void)
{
	if (ca_setup(256, 16) < 0) {
		panic("failed to setup cached allocator");
	}

	set_alarm();

	size_t allocs = bench_ca_alloc(1024);

	printf("%-12s\t%9zu allocs/second\n", "small_cache", allocs);

	ca_cleanup();
}

static void
bench_three(void)
{
	set_alarm();

	size_t allocs = bench_malloc(1024, 256);

	printf("%-12s\t%9zu allocs/second\n", "just_malloc", allocs);
}

int
main(void)
{
	trap_signals();

	bench_three();
	puts("");
	bench_two();
	bench_one();
	bench_four();

	exit(EXIT_SUCCESS);
}