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