#!/usr/bin/env python3 """Evict a file's clean pages from the page cache (posix_fadvise DONTNEED, no root); report the resident share before/after (mincore).""" import os, sys, ctypes, ctypes.util libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True) libc.mmap.restype = ctypes.c_void_p libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_long] libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t] libc.mincore.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] PAGE = os.sysconf("SC_PAGE_SIZE") def resident(p): sz = os.path.getsize(p); fd = os.open(p, os.O_RDONLY) addr = libc.mmap(None, sz, 1, 1, fd, 0) # PROT_READ, MAP_SHARED pages = (sz + PAGE - 1) // PAGE; vec = (ctypes.c_ubyte * pages)() libc.mincore(addr, sz, vec); n = sum(v & 1 for v in bytes(vec)) libc.munmap(addr, sz); os.close(fd); return n / pages for p in sys.argv[1:]: before = resident(p); fd = os.open(p, os.O_RDONLY); os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED); os.close(fd) print(f"{os.path.basename(p)} resident {before:.1%} -> {resident(p):.1%}", flush=True)