python / python/cpython

pstats.Stats.get_stats_profile can't handle functions with the same name

未关闭
#126,850 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

MCVE

import cProfile
import time
import pstats


class A:
    def foo(self):
        time.sleep(1)


class B:
    def foo(self):
        time.sleep(2)


pr = cProfile.Profile()
pr.enable()
A().foo()
B().foo()
pr.create_stats()

ps = pstats.Stats(pr).sort_stats("cumtime")
ps.print_stats(5)

when I ran this in a jupyter notebook, this outputted:

         61 function calls in 3.003 seconds

   Ordered by: cumulative time
   List reduced from 21 to 5 due to restriction <5>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        3    0.000    0.000    3.003    1.001 /usr/local/my_venv/lib/python3.10/site-packages/IPython/core/interactiveshell.py:3424(run_code)
        3    0.000    0.000    3.002    1.001 {built-in method builtins.exec}
        2    3.002    1.501    3.002    1.501 {built-in method time.sleep}
        1    0.000    0.000    2.002    2.002 /usr/tmp/ipykernel_104016/1099215389.py:12(foo)
        1    0.000    0.000    1.000    1.000 /usr/tmp/ipykernel_104016/1099215389.py:7(foo)

which correctly shows two different versions of a function called foo. However, due to the API design of get_stats_profile, only one of the functions will be stored in the dict FunctionProfile.func_profiles, the one which is last in the insertion order, which in this case since I sorted by cumtime will be A.foo:

print(ps.get_stats_profile().func_profiles["foo"])

outputs:

FunctionProfile(ncalls='1', tottime=0.0, percall_tottime=0.0, cumtime=1.0, percall_cumtime=1.0, file_name='/usr/tmp/ipykernel_104016/1099215389.py', line_number=7)

Maybe get_stats_profile should key the func_profile dictionary on something that's actually unique per profile entry, like filename:lineno(function)?

CPython versions tested on:

3.10

Operating systems tested on:

Linux

Linked PRs
  • gh-149618

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 pstats.Stats.get_stats_profile 开始,检查 FunctionProfile.func_profiles 的填充和键控方式。使用 A.foo 和 B.foo 重现所提供的 MCVE,然后验证返回的 profile 数据中两个同名函数仍然可以区分。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
tooling
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。