blob: 7a382b1da51cab19d15bfdbd5055737b56e5bbbd [file] [log] [blame]
David Reiss3000b5b2008-03-31 21:38:29 +00001#define _GNU_SOURCE
2#include <stdlib.h>
3#include <stdio.h>
4#include <time.h>
5#include <dlfcn.h>
6
7int copies;
8int non_copies;
9
10void *realloc(void *ptr, size_t size) {
11 static void *(*real_realloc)(void*, size_t) = NULL;
12 if (real_realloc == NULL) {
13 real_realloc = (void* (*) (void*, size_t)) dlsym(RTLD_NEXT, "realloc");
14 }
15
16 void *ret_ptr = (*real_realloc)(ptr, size);
17
18 if (ret_ptr == ptr) {
19 non_copies++;
20 } else {
21 copies++;
22 }
23
24 return ret_ptr;
25}
26
27
28struct TMemoryBuffer {
29 void* ptr;
30 int size;
31};
32
33int main(int argc, char *argv[]) {
34 int num_buffers;
35 int init_size;
36 int max_size;
37 int doublings;
38 int iterations;
39
40 if (argc < 6 ||
41 argc > 7 ||
42 (num_buffers = atoi(argv[1])) == 0 ||
43 (init_size = atoi(argv[2])) == 0 ||
44 (max_size = atoi(argv[3])) == 0 ||
45 init_size > max_size ||
46 (iterations = atoi(argv[4])) == 0 ||
47 (doublings = atoi(argv[5])) == 0 ||
48 (argc == 7 && atoi(argv[6]) == 0)) {
49 fprintf(stderr, "usage: realloc_test <num_buffers> <init_size> <max_size> <doublings> <iterations> [seed]\n");
50 exit(EXIT_FAILURE);
51 }
52
53 for ( int i = 0 ; i < argc ; i++ ) {
54 printf("%s ", argv[i]);
55 }
56 printf("\n");
57
58 if (argc == 7) {
59 srand(atoi(argv[6]));
60 } else {
61 srand(time(NULL));
62 }
63
64 struct TMemoryBuffer* buffers = calloc(num_buffers, sizeof(*buffers));
65 if (buffers == NULL) abort();
66
67 for ( int i = 0 ; i < num_buffers ; i++ ) {
68 buffers[i].size = max_size;
69 }
70
71 while (iterations --> 0) {
72 for ( int i = 0 ; i < doublings * num_buffers ; i++ ) {
73 struct TMemoryBuffer* buf = &buffers[rand() % num_buffers];
74 buf->size *= 2;
75 if (buf->size <= max_size) {
76 buf->ptr = realloc(buf->ptr, buf->size);
77 } else {
78 free(buf->ptr);
79 buf->size = init_size;
80 buf->ptr = malloc(buf->size);
81 }
82 if (buf->ptr == NULL) abort();
83 }
84 }
85
86 printf("Non-copied %d/%d (%.2f%%)\n", non_copies, copies + non_copies, 100.0 * non_copies / (copies + non_copies));
87 return 0;
88}