python cprofile 显示了很多信息。可以只限制我的代码吗

问题描述 投票:0回答:2

cProfile
在输出中显示了许多内置函数调用。我们可以将输出限制为仅我编写的代码吗?因此,在下面的示例中,我只能看到来自
testrun
的行或从驻留在同一脚本中的
testrun()
调用的函数吗?或者可能会将记录的呼叫级别限制为 2 或 3 ?

pr = cProfile.Profile()
pr.enable()
testrun()
pr.disable()
pr.print_stats(sort='time')
python cprofile
2个回答
3
投票

您可以过滤输出,如这个问题所示。

因此,例如,您可以按模块名称进行过滤,参见,

print_stats()

pr.sort_stats("time").print_stats("dir_or_module_name")  # replace dir_or_module_name

只需确保之前调用

strip_dirs()
,因为这可能会删除您的目录/模块名称。


编辑:您甚至可以按多个名称进行过滤,因为

print_stats()
应该接受正则表达式:

pr.print_stats("dir1|dir2|module1")

0
投票

不确定 Valentin Khun 的答案适用于哪个版本的 python,但在 Python 3.12.2 中,我必须使用

cProfile
pstats
的组合来过滤结果。

这里是一个示例,展示了如何限制您的代码,同时还排除私有和魔术可调用对象

MRE

from cProfile import Profile
from pstats import Stats
from time import sleep


def hello() -> None:
    print("Hello World!")
    sleep(1)


def _private() -> None:
    some_list = []
    for i in range(10):
        some_list.append(i)


def main() -> None:
    hello()
    _private()


if __name__ == '__main__':
    # Using ``Profile`` as a context manager.
    # https://docs.python.org/3.12/library/profile.html#profile.Profile
    with Profile() as pr:
        main()

    stats = Stats(pr).sort_stats("cumtime")
    stats.print_stats(r"\((?!\_).*\)$")  # Exclude private and magic callables.

输出

...\scratches\scratch.py 
Hello World!
         17 function calls in 1.000 seconds

   Ordered by: cumulative time
   List reduced from 8 to 2 due to restriction <'\\((?!\\_).*\\)$'>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.000    1.000 ...\scratches\scratch.py:17(main)
        1    0.000    0.000    1.000    1.000 ...\scratches\scratch.py:6(hello)

© www.soinside.com 2019 - 2024. All rights reserved.