2 * POSIX lock performance test 1
4 * Fork off a given number of children who attempt to repeatedly acquire a
5 * POSIX write lock over the whole file and then release it for a given number
6 * of times. Time this to get a rough indication of locking performance for
7 * a single, contended whole-file lock.
12 #endif /* HAVE_CONFIG_H */
15 #include <sys/types.h>
20 #include <sys/types.h>
31 #define NRLOCK (10240)
33 static struct timespec *diff;
36 lockunlock(const char *name, int nrlock, struct timespec *slot,
37 bool verbose, bool yield)
40 struct flock lck = { .l_whence = SEEK_SET };
41 struct timespec start, end;
44 fd = open(name, O_CREAT|O_RDWR, 0644);
50 ret = clock_gettime(CLOCK_MONOTONIC_RAW, &start);
52 perror("clock_gettime");
56 for (i = 0; i < nrlock; ++i) {
58 ret = fcntl(fd, F_SETLKW, &lck);
65 printf("pid:%u\n", pid);
68 ret = fcntl(fd, F_SETLKW, &lck);
74 /* yield CPU to give another worker a chance */
79 clock_gettime(CLOCK_MONOTONIC_RAW, &end);
81 perror("clock_gettime");
86 *slot = timespec_sub(end, start);
93 printf("usage: %s [-n nr_procs] [-l nr_locks] [-v] [-y] filename\n", prog);
97 main(int argc, char **argv)
99 bool verbose = false, yield = false;
100 int i, opt, valid = 0;
104 struct timespec total = { .tv_sec = 0,
107 while ((opt = getopt(argc, argv, "l:n:vy")) != -1) {
110 nlock = atoi(optarg);
113 nproc = atoi(optarg);
132 pids = calloc(nproc, sizeof(pid_t));
134 fprintf(stderr, "Unable to allocate pids array!");
138 diff = mmap(0, nproc * sizeof(*diff), PROT_READ | PROT_WRITE,
139 MAP_ANONYMOUS | MAP_SHARED, -1, 0);
140 if (diff == (struct timespec *)-1) {
141 fprintf(stderr, "Unable to allocate timespec array!");
145 for (i = 0; i < nproc; ++i) {
148 return lockunlock(argv[optind], nlock,
149 &diff[i], verbose, yield);
152 for (i = 0; i < nproc; ++i) {
156 fprintf(stderr, "process %d failed to fork\n", i);
159 if (waitpid(pids[i], &status, 0) < 0) {
160 fprintf(stderr, "unable to reap pid %d\n", pids[i]);
163 if (!WIFEXITED(status) || WEXITSTATUS(status)) {
164 fprintf(stderr, "pid %d exited abnormally(0x%x)\n", pids[i],status);
167 total = timespec_add(total, diff[i]);
171 if (valid != nproc) {
172 fprintf(stderr, "Some children didn't run properly -- "
173 "requested %d but only got %d\n", nproc, valid);
177 printf("%ld.%09ld\n", total.tv_sec, total.tv_nsec);