add some comments
[tridge/junkcode.git] / lock_scaling.c
1 /*
2   demonstrate problem with linear lock lists
3
4   tridge@samba.org, February 2004
5 */
6
7 #include <stdio.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <errno.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/wait.h>
15 #include <sys/time.h>
16
17
18 static struct timeval tp1,tp2;
19
20 static double tvdiff(struct timeval *tv1, struct timeval *tv2)
21 {
22         return (tv2->tv_sec + (tv2->tv_usec*1.0e-6)) - 
23                 (tv1->tv_sec + (tv1->tv_usec*1.0e-6));
24 }
25
26 static void start_timer()
27 {
28         gettimeofday(&tp1,NULL);
29 }
30
31 static double end_timer()
32 {
33         gettimeofday(&tp2,NULL);
34         fflush(stdout);
35         return tvdiff(&tp1, &tp2);
36 }
37
38 static int brlock(int fd, off_t offset, int rw_type, int lck_type)
39 {
40         struct flock fl;
41         int ret;
42
43         fl.l_type = rw_type;
44         fl.l_whence = SEEK_SET;
45         fl.l_start = offset;
46         fl.l_len = 1;
47         fl.l_pid = 0;
48
49         ret = fcntl(fd,lck_type,&fl);
50
51         if (ret == -1) {
52                 printf("brlock failed offset=%d rw_type=%d lck_type=%d : %s\n", 
53                        (int)offset, rw_type, lck_type, strerror(errno));
54         }
55         return 0;
56 }
57
58
59 int main(int argc, char *argv[])
60 {
61         int i, fd;
62         int nlocks;
63         const char *fname = "lock_scaling.dat";
64
65         if (argc < 2) {
66                 printf("Usage: lock_scaling <nlocks>\n");
67                 exit(1);
68         }
69
70         nlocks = atoi(argv[1]);
71
72         fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0600);
73         if (fd == -1) {
74                 perror(fname);
75                 exit(1);
76         }
77
78         for (i=0;i<nlocks;i++) {
79                 brlock(fd, 2*i, F_WRLCK, F_SETLKW);
80         }
81
82         while (1) {
83                 int count=0;
84                 double t;
85                 start_timer();
86
87                 while ((t=end_timer()) < 1.0) {
88                         brlock(fd, 2*nlocks, F_WRLCK, F_SETLKW);
89                         brlock(fd, 2*nlocks, F_UNLCK, F_SETLKW);
90                         count++;
91                 }
92                 printf("%.1f locks/sec\r", count/t);
93                 fflush(stdout);
94         }
95
96
97         return 0;
98 }