问题描述
我正在使用 cProfile
在 Python 中进行分析.我发现了一个需要大量 CPU 时间的函数.我如何找出哪个函数最常调用这个重函数?
I'm profiling in Python using cProfile
. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?
我会解决一个变通方法:我可以在那个沉重的函数中编写一行 Python 代码来打印调用它的函数的名称吗?
I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?
推荐答案
这可能不会直接回答您的问题,但肯定会有所帮助.如果使用带有选项 --sort 累积的探查器,它将按累积时间对函数进行排序.这不仅有助于检测重函数,还有助于检测调用它们的函数.
That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.
python -m cProfile --sort cumulative myScript.py
有一个获取调用者函数的解决方法:
There is a workaround to get the caller function:
import inspect
print inspect.getframeinfo(inspect.currentframe().f_back)[2]
您可以添加任意数量的 f_back,以防您想要来电者等如果你想计算频繁调用,你可以这样做:
You can add as many f_back as you want in case you want the caller caller etcIf you want to calculate frequent calls you can do this:
record = {}
caller = inspect.getframeinfo(inspect.currentframe().f_back)[2]
record[caller] = record.get(caller, 0) + 1
然后按频率顺序打印它们:
Then print them by order of frequency:
print sorted(record.items(), key=lambda a: a[1])
这篇关于在 Python 中进行分析:谁调用了该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!