Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778#!/usr/bin/env python3"""Launch a binary and sample its memory until it exits or time runs out.
Footprint is what Activity Monitor shows: the process's dirty memory,including GPU driver memory that is not mapped into the process. RSS is whatbtop and ps show: resident pages mapped into the process, including sharedlibrary code but not unmapped GPU memory. Footprint needs macOS; elsewhereonly RSS is sampled.
Usage: scripts/memory.py <binary> [seconds]"""
import reimport shutilimport subprocessimport sysimport time
INTERVAL = 0.5# Keep breakdown rows of at least 1 MB, plus the header and totals.BREAKDOWN_ROW = re.compile(r"^\s*[\d.]+ [MG]B\s|Category|TOTAL|phys_footprint")
def run(*command): return subprocess.run(command, capture_output=True, text=True).stdout
def footprint_bytes(pid): output = run("footprint", "--noCategories", "-f", "bytes", "-p", str(pid)) match = re.search(r"phys_footprint: (\d+) B", output) return int(match.group(1)) if match else None
def rss_bytes(pid): output = run("ps", "-o", "rss=", "-p", str(pid)).strip() return int(output) * 1024 if output else None
def mib(value): return "-" if value is None else f"{value / 1048576:.0f} MiB"
def main(): if len(sys.argv) < 2: sys.exit(__doc__) binary = sys.argv[1] seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 6.0 has_footprint = sys.platform == "darwin" and shutil.which("footprint") is not None
process = subprocess.Popen( [binary], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) start = time.monotonic() try: print(f"{'time':>6} {'footprint':>10} {'rss':>9}") while process.poll() is None: elapsed = time.monotonic() - start if elapsed >= seconds: break footprint = footprint_bytes(process.pid) if has_footprint else None print(f"{elapsed:5.1f}s {mib(footprint):>10} {mib(rss_bytes(process.pid)):>9}") time.sleep(INTERVAL)
if process.poll() is not None: print(f"exited early with status {process.returncode}") elif has_footprint: print() for line in run("footprint", "-p", str(process.pid)).splitlines(): if BREAKDOWN_ROW.search(line): print(line) finally: process.terminate() process.wait()
if __name__ == "__main__": main()