← 中文资源

简体中文版本

tracemalloc 快照定位内存热点

启动 tracemalloc,在构建索引前后各取一次快照,按行比较分配位置,并读取当前与峰值内存。

阅读英文原文

实现说明

整个示例围绕函数 build_index、main组织。 for stat in second.compare_to(first, 'lineno')[:3] 是唯一的迭代点——其余代码顺序执行一遍。 返回的是新建的值,不复用入参。

使用要点

  • 依赖检查:tracemalloc——不是内建的,项目里必须有。
  • 每一步打印都带着自己的标签:size diff:、current bytes:、peak bytes:。
  • main 的演示流程是 build_index——跑一遍文件,这条流程从头到尾可见。

常见问题

build_index 会修改传入的参数吗?

没有原地修改——函数读取输入并返回新值。

需要安装第三方包吗?

需要——tracemalloc。运行前请先加入项目依赖。

主要签名是 def build_index(rows: int) -> dict[int, str]

核心语句

return {row: 'user-' + str(row) for row in range(rows)}

代码示例

import tracemalloc


def build_index(rows: int) -> dict[int, str]:
    return {row: 'user-' + str(row) for row in range(rows)}


def main() -> None:
    tracemalloc.start(10)

    first = tracemalloc.take_snapshot()
    index = build_index(20_000)
    second = tracemalloc.take_snapshot()

    for stat in second.compare_to(first, 'lineno')[:3]:
        print('size diff:', stat.size_diff, 'count diff:', stat.count_diff)

    current, peak = tracemalloc.get_traced_memory()
    print('current bytes:', current)
    print('peak bytes:', peak)
    print('index entries:', len(index))

    tracemalloc.stop()


if __name__ == '__main__':
    main()