cProfile
在输出中显示了许多内置函数调用。我们可以将输出限制为仅我编写的代码吗?因此,在下面的示例中,我只能看到来自 testrun
的行或从驻留在同一脚本中的 testrun()
调用的函数吗?或者可能会将记录的呼叫级别限制为 2 或 3 ?
pr = cProfile.Profile()
pr.enable()
testrun()
pr.disable()
pr.print_stats(sort='time')
您可以过滤输出,如这个问题所示。
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")
不确定 Valentin Khun 的答案适用于哪个版本的 python,但在 Python 3.12.2 中,我必须使用
cProfile
和 pstats
的组合来过滤结果。
这里是一个示例,展示了如何限制您的代码,同时还排除私有和魔术可调用对象。
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)