Created
May 8, 2020 23:38
-
-
Save kkourt/1aa98e1acf7e587280d06f143b1a74ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <inttypes.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <sys/mman.h> | |
#include <sys/time.h> | |
#include <fcntl.h> | |
int main(int argc, char **argv) { | |
int opt; | |
const char *fname = NULL; | |
unsigned long npages = 0; | |
bool sequential = false; | |
while ((opt = getopt(argc, argv, "f:n:s")) != -1) { | |
switch (opt) { | |
case 'f': | |
fname = optarg; | |
break; | |
case 'n': | |
npages = strtoul(optarg, NULL, 10); | |
break; | |
case 's': | |
sequential = true; | |
} | |
} | |
if (fname == NULL || npages == 0) { | |
fprintf(stderr, "Usage: %s -f <fname> -n npages [-s ]\n", argv[0]); | |
exit(1); | |
} | |
int fd = open(fname, O_RDONLY); | |
if (fd == -1) { | |
perror(fname); | |
exit(1); | |
} | |
size_t len = npages*4096; | |
void *ptr = mmap(0, len, PROT_READ, MAP_SHARED, fd, 0); | |
if (ptr == (void *)-1) { | |
perror("mmap"); | |
exit(1); | |
} | |
if (sequential) { | |
int ret = madvise(ptr, len, MADV_SEQUENTIAL); | |
if (ret == -1) { | |
perror("mmap"); | |
exit(1); | |
} | |
} | |
struct timeval tv_start, tv_end; | |
gettimeofday(&tv_start, NULL); | |
unsigned long sum = 0; | |
unsigned long *elems = ptr; | |
for (unsigned long i=0; i < len / sizeof(*elems); i++) { | |
sum += elems[i]; | |
} | |
gettimeofday(&tv_end, NULL); | |
size_t usecs = (tv_end.tv_sec - tv_start.tv_sec) * 1000000; | |
usecs += tv_end.tv_usec; | |
usecs -= tv_start.tv_usec; | |
double secs = usecs / 1000000.0; | |
double mib = (double)len / (1024*1024.0); | |
printf("MADV_SEQUENTIAL=%u time:%zuus tput:%.1lf MiB/s (%.1lf MiB) sum=%lu\n", sequential, usecs, mib / secs, mib, sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment