stage20-resource-consumption.py
TEXT FILE722 B · Public source code for developers, search crawlers and AI agents
1import tracemalloc
2from time import perf_counter_ns, process_time_ns
3
4def profile(operation):
5 if tracemalloc.is_tracing():
6 raise RuntimeError("requires independent tracing session")
7 tracemalloc.start()
8 try:
9 wall, cpu = perf_counter_ns(), process_time_ns()
10 operation()
11 elapsed, consumed = perf_counter_ns()-wall, process_time_ns()-cpu
12 _, peak = tracemalloc.get_traced_memory()
13 return {"wall_ns": elapsed, "cpu_ns": consumed, "python_peak_bytes": peak}
14 finally:
15 tracemalloc.stop()
16
17if __name__ == "__main__":
18 result = profile(lambda: list(range(10000)))
19 assert result["python_peak_bytes"] > 0 and not tracemalloc.is_tracing()
20 print(result)Read-only source · Select a line number to link directly · Raw download above
