我使用cProfile在Python中进行cProfile 。 我发现一个需要大量CPU时间的功能。 最重要的功能是什么?
编辑:
我会解决一个解决方法:我可以在那个重要的函数中编写一个Python行,它将打印调用它的函数的名称?
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?
EDIT:
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累积的分析器,它将按累积时间对功能进行排序。 这有助于检测不仅重要的功能,而且检测它们的功能。
python -m cProfile --sort cumulative myScript.py有一个解决方法来获取调用者的功能:
import inspect print inspect.getframeinfo(inspect.currentframe().f_back)[2]您可以添加任意数量的f_back,以防您想要呼叫方来电等待。如果要计算频繁呼叫,您可以这样做:
record = {} caller = inspect.getframeinfo(inspect.currentframe().f_back)[2] record[caller] = record.get(caller, 0) + 1然后按照频率顺序打印:
print sorted(record.items(), key=lambda a: a[1])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.pyThere is a workaround to get the caller function:
import inspect print inspect.getframeinfo(inspect.currentframe().f_back)[2]You can add as many f_back as you want in case you want the caller caller etc If 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) + 1Then print them by order of frequency:
print sorted(record.items(), key=lambda a: a[1])更多推荐
发布评论