示例工程 24-profiling-performance

24-profiling-performance/03-tracemalloc-top/tracemalloc_top.py

python · 0.7 KB

"""用 tracemalloc 快照找最大分配点。"""
 
from __future__ import annotations
 
import tracemalloc
 
 
def allocate(count: int = 10_000) -> list[str]:
    return [f"item-{value}" for value in range(count)]
 
 
def top_allocations(count: int = 10_000) -> tuple[int, list[str]]:
    tracemalloc.start()
    try:
        data = allocate(count)
        snapshot = tracemalloc.take_snapshot()
        stats = snapshot.statistics("lineno")
        lines = [f"{stat.size / 1024:.1f} KiB {stat.traceback}" for stat in stats[:3]]
        return len(data), lines
    finally:
        tracemalloc.stop()
 
 
def main() -> None:
    count, lines = top_allocations()
    print(f"items: {count}")
    for line in lines:
        print(line)
 
 
if __name__ == "__main__":
    main()