Last active
June 4, 2016 16:04
-
-
Save alex-hofsteede/653f89ee1cfd1d212753 to your computer and use it in GitHub Desktop.
The simplest possible utility to determine how many pages of a file are in the page cache
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
#define _BSD_SOURCE | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
#include <stdint.h> | |
#include <unistd.h> | |
/* | |
* COMPILE: | |
* cc -std=c99 fincore.c -o fincore | |
* USE: | |
* ./fincore [FILE]... | |
* OUTPUT: | |
* pages_in_file pages_in_cache filename | |
*/ | |
int main(int argc, const char *argv[]) { | |
for (int i = 1; i < argc; i++) { | |
int fd = open(argv[i], O_RDONLY); | |
if (fd != -1) { | |
struct stat stats; | |
int s = fstat(fd, &stats); | |
if (s != -1) { | |
void *map = mmap(NULL, stats.st_size, PROT_NONE, MAP_SHARED, fd, 0); | |
if (map != MAP_FAILED) { | |
size_t pages = (stats.st_size + sysconf(_SC_PAGESIZE) - 1) / sysconf(_SC_PAGESIZE); | |
char *incore = calloc(pages, sizeof(uint8_t)); | |
mincore(map, stats.st_size, incore); | |
size_t cached = 0; | |
for (size_t j = 0; j < pages; j++) { | |
cached += incore[j] & 0x01; | |
} | |
printf("%zu\t%zu\t%s\n", pages, cached, argv[i]); | |
munmap(map, stats.st_size); | |
} | |
} | |
close(fd); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment