aboutsummaryrefslogtreecommitdiff
path: root/src/benchmarks/loop/loop.c
blob: 9593cd535bf3eaf131984cb9b1812023db6ae019 (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
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
#include <assert.h>
#include <malloc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


static size_t _rand() {
	static __thread size_t seed = 123456789;
	size_t a = 1103515245;
	size_t c = 12345;
	size_t m = 1 << 31;
	seed = (a * seed + c) % m;
	return seed;
}

typedef struct ThreadArgs {
	double benchmark;
	int allocations;
	int max_size;
#ifdef KEEP_ALLOCS
	int num_to_keep;
#endif
} ThreadArgs;

static void* test_thread_func(void* arg) {
	ThreadArgs* args = (ThreadArgs*)arg;
#ifdef KEEP_ALLOCS
	void** ptrs = (void**)calloc(args->num_to_keep, sizeof(void*));
#endif

	for(int i = 0; i < args->allocations; i++) {
#ifdef KEEP_ALLOCS
		int pos = i % args->num_to_keep;
		if (0 == pos && i > 0) {
			for (int j = 0; j < args->num_to_keep; j++)
				free(ptrs[j]);
		}
		ptrs[pos] = malloc((_rand() % args->max_size) + 1);
#else
		void* ptr = malloc((_rand() % args->max_size) + 1);
		free(ptr);
#endif
	}
	return NULL;
}

int main(int argc, char* argv[]) {
	pthread_t* threads;
	int num_threads;
	struct ThreadArgs thread_args;

#ifdef KEEP_ALLOCS
	if (argc < 5) {
		fprintf(stderr, "Usage: %s <num threads> <num allocations> <max size> <allocs to keep>\n", argv[0]);
		return 1;
	}
#else
	if (argc < 4) {
		fprintf(stderr, "Usage: %s <num threads> <num allocations> <max size>\n", argv[0]);
		return 1;
	}
#endif

	num_threads = atoi(argv[1]);
	thread_args.allocations = atoi(argv[2]);
	thread_args.max_size = atoi(argv[3]);
#ifdef KEEP_ALLOCS
	thread_args.num_to_keep = atoi(argv[4]);
#endif

	threads = (pthread_t*)malloc(num_threads * sizeof(pthread_t));

	for (int i = 0; i < num_threads; i++) {
		if (0 != pthread_create(&threads[i], NULL, test_thread_func, &thread_args)) {
			perror("pthread_create");
			return 1;
		}
	}

	for(int i = 0; i < num_threads; i++) {
		if (0 != pthread_join(threads[i], NULL)) {
			perror("pthread_join");
			return 1;
		}
	}

	if (argc == 6)
	{
		FILE* f = stdout;
		if (strcmp(argv[4],"stdout") != 0)
			f = fopen(argv[4], "w");
		malloc_info(0, f);
		if (strcmp(argv[4],"stdout") != 0)
			fclose(f);
	}

	return 0;
}