Add proper per-file copyright notices/licenses and top-level license.
[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     const char *filename;
15     int thread_num;
16     long long timestamp;
17 };
18
19 #define MAX_THREADS 128
20 struct thread_state threads[MAX_THREADS];
21
22 int64_t now_hires()
23 {
24     struct timespec time;
25
26     if (clock_gettime(CLOCK_REALTIME, &time) != 0) {
27         perror("clock_gettime");
28         return 0;
29     }
30
31     return (int64_t)(time.tv_sec) * 1000000000 + time.tv_nsec;
32 }
33
34 #if 0
35 void bench_write()
36 {
37     FILE *f = fopen("writetest", "wb");
38     if (f == NULL) {
39         perror("fopen");
40         return;
41     }
42
43     char buf[4096];
44     for (int i = 0; i < 16; i++) {
45         int64_t start, end;
46         start = now_hires();
47         rewind(f);
48         fwrite(buf, 1, sizeof(buf), f);
49         fflush(f);
50         end = now_hires();
51         printf("Pass %d: Time = %"PRIi64"\n", i, end - start);
52     }
53 }
54 #endif
55
56 void *benchmark_thread(void *arg)
57 {
58     struct thread_state *ts = (struct thread_state *)arg;
59
60     printf("Opening %s\n", ts->filename);
61
62     int64_t start, end;
63
64     start = now_hires();
65
66     //struct stat stat_buf;
67     //stat(namebuf, &stat_buf);
68
69     FILE *f = fopen(ts->filename, "rb");
70     if (f == NULL) {
71         perror("fopen");
72         return NULL;
73     }
74
75     char buf[65536];
76     while (fread(buf, 1, sizeof(buf), f) > 0) { }
77
78     end = now_hires();
79     printf("Thread %d: Time = %"PRIi64"\n", ts->thread_num, end - start);
80
81     fclose(f);
82
83     return NULL;
84 }
85
86 void launch_thread(int i, const char *filename)
87 {
88     threads[i].thread_num = i;
89     threads[i].filename = filename;
90     printf("Launching thread %d [%s]...\n", i, filename);
91     if (pthread_create(&threads[i].thread, NULL, benchmark_thread, &threads[i]) != 0) {
92         fprintf(stderr, "Error launching thread!\n");
93         exit(1);
94     }
95 }
96
97 void wait_thread(int n)
98 {
99     void *result;
100     pthread_join(threads[n].thread, &result);
101 }
102
103 int main(int argc, char *argv[])
104 {
105     int threads = argc - 1;
106
107     printf("Testing with %d threads\n", threads);
108
109     for (int i = 0; i < threads; i++) {
110         launch_thread(i, argv[i + 1]);
111     }
112
113     for (int i = 0; i < threads; i++) {
114         wait_thread(i);
115     }
116
117     return 0;
118 }