|
| 1 | +#include <stdlib.h> |
| 2 | +#include <string.h> |
| 3 | +#include <stdio.h> |
| 4 | +#include <unistd.h> |
| 5 | +#include <fcntl.h> |
| 6 | +#include <errno.h> |
| 7 | +#include <sys/mman.h> |
| 8 | +#include <sys/stat.h> |
| 9 | + |
| 10 | +int main(int argc, char* argv[]) { |
| 11 | + const char* filename = "data"; |
| 12 | + size_t sz = (size_t) -1; |
| 13 | + useconds_t delay = 0; |
| 14 | + int opt; |
| 15 | + while ((opt = getopt(argc, argv, "f:s:d:")) != -1) |
| 16 | + if (opt == 'f') |
| 17 | + filename = optarg; |
| 18 | + else if (opt == 's') |
| 19 | + sz = strtoul(optarg, NULL, 0); |
| 20 | + else if (opt == 'd') |
| 21 | + delay = (useconds_t) (strtod(optarg, NULL) * 1000000); |
| 22 | + else { |
| 23 | + fprintf(stderr, "Usage: ./maprandomtouch [-f FILE] [-s SIZE] [-d DELAY]\n"); |
| 24 | + exit(EXIT_FAILURE); |
| 25 | + } |
| 26 | + |
| 27 | + int fd = open(filename, O_RDONLY); |
| 28 | + if (fd == -1) { |
| 29 | + fprintf(stderr, "%s: %s\n", filename, strerror(errno)); |
| 30 | + exit(EXIT_FAILURE); |
| 31 | + } |
| 32 | + |
| 33 | + if (sz == (size_t) -1) { |
| 34 | + struct stat s; |
| 35 | + if (fstat(fd, &s) == 0) |
| 36 | + sz = s.st_size; |
| 37 | + } |
| 38 | + |
| 39 | + unsigned char* ptr = (unsigned char*) |
| 40 | + mmap(NULL, sz, PROT_READ, MAP_SHARED, fd, 0); |
| 41 | + printf("mapped %zu bytes at %p\n", sz, ptr); |
| 42 | + |
| 43 | + size_t npages = sz / 4096; |
| 44 | + size_t checksum = 0; |
| 45 | + for (size_t pagecount = 0; pagecount < npages; ++pagecount) { |
| 46 | + size_t pos = random() % npages; |
| 47 | + checksum += ptr[pos * 4096]; |
| 48 | + if (delay > 0) { |
| 49 | + usleep(delay); |
| 50 | + if (pagecount && pagecount % 1000 == 0) |
| 51 | + printf("touched %zu pages\n", pagecount); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + printf("checksum %zu\n", checksum); |
| 56 | + if (delay > 0) |
| 57 | + sleep(100); |
| 58 | +} |
0 commit comments