import tracemalloc from time import perf_counter_ns, process_time_ns def profile(operation): if tracemalloc.is_tracing(): raise RuntimeError("requires independent tracing session") tracemalloc.start() try: wall, cpu = perf_counter_ns(), process_time_ns() operation() elapsed, consumed = perf_counter_ns()-wall, process_time_ns()-cpu _, peak = tracemalloc.get_traced_memory() return {"wall_ns": elapsed, "cpu_ns": consumed, "python_peak_bytes": peak} finally: tracemalloc.stop() if __name__ == "__main__": result = profile(lambda: list(range(10000))) assert result["python_peak_bytes"] > 0 and not tracemalloc.is_tracing() print(result)