1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/mman.h>
7 #include <sys/time.h>
8
9 #include "pagingtest.h"
10
11 #define LINESIZE 32
12
thrashing_test(int test_runs)13 int thrashing_test(int test_runs) {
14 int fds[4] = {-1, -1, -1, -1};
15 char tmpnames[4][17] = { "thrashing1XXXXXX", "thrashing2XXXXXX", "thrashing3XXXXXX", "thrashing4XXXXXX" };
16 volatile char *bufs[4] = {0};
17 unsigned i, j;
18 long long k;
19 int ret = -1;
20 struct timeval begin_time, end_time, elapsed_time, total_time;
21 unsigned long long filesize;
22 long num_pages;
23 long pagesize;
24
25 timerclear(&total_time);
26
27 num_pages = sysconf(_SC_PHYS_PAGES);
28 pagesize = sysconf(_SC_PAGE_SIZE);
29 if (num_pages < 0) {
30 fprintf(stderr, "failed to get the number of pages\n");
31 return -1;
32 }
33
34 filesize = num_pages * pagesize / (ARRAY_SIZE(fds) - 1);
35
36 for (i = 0; i < ARRAY_SIZE(fds); i++) {
37 fds[i] = create_tmp_file(tmpnames[i], filesize);
38 if (fds[i] < 0) {
39 goto err_fd;
40 }
41 }
42
43 for (i = 0; i < ARRAY_SIZE(fds); i++) {
44 bufs[i] = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, fds[i], 0);
45 if (bufs[i] == ((void *)-1)) {
46 fprintf(stderr, "Failed to mmap file: %s\n", strerror(errno));
47 goto err;
48 }
49 }
50
51 for (i = 0; i < test_runs; i++) {
52 for (j = 0; j < ARRAY_SIZE(fds); j++) {
53 gettimeofday(&begin_time, NULL);
54 //Unfortunately when under memory pressure, fadvise and madvise stop working...
55 //Read backwards to prevent mmap prefetching
56 for (k = ((filesize - 1) & ~(pagesize - 1)); k >= 0; k -= pagesize) {
57 bufs[j][k];
58 }
59 gettimeofday(&end_time, NULL);
60
61 timersub(&end_time, &begin_time, &elapsed_time);
62 timeradd(&total_time, &elapsed_time, &total_time);
63 }
64 }
65
66 printf("thrashing: %llu MB/s\n", (filesize * ARRAY_SIZE(fds) * test_runs * USEC_PER_SEC) /
67 (1024 * 1024 * (total_time.tv_sec * USEC_PER_SEC + total_time.tv_usec)));
68
69 ret = 0;
70
71 err:
72 for (i = 0; i < ARRAY_SIZE(bufs) && bufs[i] != NULL; i++) {
73 munmap((void *)bufs[i], filesize);
74 }
75 err_fd:
76 for (i = 0; i < ARRAY_SIZE(fds) && fds[i] >= 0; i++) {
77 close(fds[i]);
78 }
79 return ret;
80 }
81