Add proper per-file copyright notices/licenses and top-level license.
[bluesky.git] / microbench / statbench.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 void *benchmark_thread(void *arg)
34 {
35     struct thread_state *ts = (struct thread_state *)arg;
36
37     char namebuf[64];
38     sprintf(namebuf, "file-%d", ts->thread_num + 1);
39     printf("Opening %s\n", namebuf);
40
41     int64_t start, end;
42
43     start = now_hires();
44
45     struct stat stat_buf;
46     stat(namebuf, &stat_buf);
47
48     end = now_hires();
49     printf("Thread %d: Time = %"PRIi64"\n", ts->thread_num, end - start);
50
51     return NULL;
52 }
53
54 void launch_thread(int i)
55 {
56     threads[i].thread_num = i;
57     printf("Launching thread %d...\n", i);
58     if (pthread_create(&threads[i].thread, NULL, benchmark_thread, &threads[i]) != 0) {
59         fprintf(stderr, "Error launching thread!\n");
60         exit(1);
61     }
62 }
63
64 void wait_thread(int n)
65 {
66     void *result;
67     pthread_join(threads[n].thread, &result);
68 }
69
70 int main(int argc, char *argv[])
71 {
72     int threads = 8;
73
74     if (argc > 1)
75         threads = atoi(argv[1]);
76     if (threads > MAX_THREADS)
77         threads = MAX_THREADS;
78
79     printf("Testing with %d threads\n", threads);
80
81     for (int i = 0; i < threads; i++) {
82         launch_thread(i);
83     }
84
85     for (int i = 0; i < threads; i++) {
86         wait_thread(i);
87     }
88
89     return 0;
90 }