"""macOS page-cache helpers (no sudo needed). - nocache_copy: copy a file with F_NOCACHE on both ends, so the new file's pages are not left in the unified buffer cache. The first read of the copy then has to come from the SSD ("cold disk"). - resident_fraction: mincore() over an mmap of the file, to check how much of it is actually in RAM right before we load it. """ import ctypes import ctypes.util import fcntl import mmap import os F_NOCACHE = getattr(fcntl, "F_NOCACHE", 48) _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] def nocache_copy(src: str, dst: str, chunk: int = 64 << 20) -> None: with open(src, "rb", buffering=0) as fi, open(dst, "wb", buffering=0) as fo: fcntl.fcntl(fi.fileno(), F_NOCACHE, 1) fcntl.fcntl(fo.fileno(), F_NOCACHE, 1) while True: b = fi.read(chunk) if not b: break fo.write(b) os.fsync(fo.fileno()) def resident_fraction(path: str): """Fraction of the file's pages resident in memory, or None if unknown.""" try: size = os.path.getsize(path) if size == 0: return 0.0 page = mmap.PAGESIZE npages = (size + page - 1) // page with open(path, "rb") as f: # Map with libc directly: mapping alone does not fault pages in. addr = _libc.mmap(None, ctypes.c_size_t(size), mmap.PROT_READ, mmap.MAP_SHARED, f.fileno(), ctypes.c_long(0)) if addr in (None, ctypes.c_void_p(-1).value): return None try: vec = (ctypes.c_char * npages)() if _libc.mincore(ctypes.c_void_p(addr), ctypes.c_size_t(size), vec) != 0: return None return sum(1 for v in vec.raw if v & 1) / npages finally: _libc.munmap(ctypes.c_void_p(addr), ctypes.c_size_t(size)) except Exception: return None