Add scripts for automatically testing reads at different settings.
[bluesky.git] / microbench / readbench.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <inttypes.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <time.h>
8 #include <pthread.h>
9
10 struct thread_state {
11     pthread_t thread;
12     int thread_num;
13     long long timestamp;
14 };
15
16 #define MAX_THREADS 128
17 struct thread_state threads[MAX_THREADS];
18
19 int64_t now_hires()
20 {
21     struct timespec time;
22
23     if (clock_gettime(CLOCK_REALTIME, &time) != 0) {
24         perror("clock_gettime");
25         return 0;
26     }
27
28     return (int64_t)(time.tv_sec) * 1000000000 + time.tv_nsec;
29 }
30
31 #if 0
32 void bench_write()
33 {
34     FILE *f = fopen("writetest", "wb");
35     if (f == NULL) {
36         perror("fopen");
37         return;
38     }
39
40     char buf[4096];
41     for (int i = 0; i < 16; i++) {
42         int64_t start, end;
43         start = now_hires();
44         rewind(f);
45         fwrite(buf, 1, sizeof(buf), f);
46         fflush(f);
47         end = now_hires();
48         printf("Pass %d: Time = %"PRIi64"\n", i, end - start);
49     }
50 }
51 #endif
52
53 void *benchmark_thread(void *arg)
54 {
55     struct thread_state *ts = (struct thread_state *)arg;
56
57     char namebuf[64];
58     sprintf(namebuf, "file-%d", ts->thread_num + 1);
59     printf("Opening %s\n", namebuf);
60
61     int64_t start, end;
62
63     start = now_hires();
64     FILE *f = fopen(namebuf, "rb");
65     if (f == NULL) {
66         perror("fopen");
67         return NULL;
68     }
69
70     char buf[4096];
71     fread(buf, 1, sizeof(buf), f);
72
73     end = now_hires();
74     printf("Thread %d: Time = %"PRIi64"\n", ts->thread_num, end - start);
75
76     fclose(f);
77
78     return NULL;
79 }
80
81 void launch_thread(int i)
82 {
83     threads[i].thread_num = i;
84     printf("Launching thread %d...\n", i);
85     if (pthread_create(&threads[i].thread, NULL, benchmark_thread, &threads[i]) != 0) {
86         fprintf(stderr, "Error launching thread!\n");
87         exit(1);
88     }
89 }
90
91 void wait_thread(int n)
92 {
93     void *result;
94     pthread_join(threads[n].thread, &result);
95 }
96
97 int main(int argc, char *argv[])
98 {
99     int threads = 8;
100
101     if (argc > 1)
102         threads = atoi(argv[1]);
103     if (threads > MAX_THREADS)
104         threads = MAX_THREADS;
105
106     printf("Testing with %d threads\n", threads);
107
108     for (int i = 0; i < threads; i++) {
109         launch_thread(i);
110     }
111
112     for (int i = 0; i < threads; i++) {
113         wait_thread(i);
114     }
115
116     return 0;
117 }