示例工程 24-profiling-performance

24-profiling-performance/02-profile-hotspot/README.md

markdown · 1.0 KB

# 02 · profile-hotspot
 
**演示**:用 `cProfile` + `pstats` 按 `tottime` 排序,热点直接指向 `list.index`(O(n²) 的根源),而不是猜「循环慢」。
**运行**:
 
```sh
uv run python examples/24-profiling-performance/02-profile-hotspot/profile_hotspot.py
```
 
**预期输出**(3.12.9,耗时会波动;表头与排名稳定):
 
```text
         3002 function calls in 0.010 seconds
 
   Ordered by: internal time
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     2500    0.010    0.000    0.010    0.000 {method 'index' of 'list' objects}
        1    0.000    0.000    0.010    0.010 .../profile_hotspot.py:10(find_duplicates)
      500    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
...
duplicates: 500
```
 
**依赖**:仅标准库。
**注意**:`tottime` 是函数自身耗时(不含子调用),`cumtime` 含子调用;找热点先看 `tottime`,理解调用链看 `cumtime`。