Skip to content

Instantly share code, notes, and snippets.

@alex-hofsteede
Last active June 4, 2016 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-hofsteede/653f89ee1cfd1d212753 to your computer and use it in GitHub Desktop.
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
#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