Python中的分析:谁调用函数?(Profiling in Python: Who called the function?)

编程入门 行业动态 更新时间:2024-10-25 11:19:51
Python中的分析:谁调用函数?(Profiling in Python: Who called the function?)

我使用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.py

There 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) + 1

Then print them by order of frequency:

print sorted(record.items(), key=lambda a: a[1])

更多推荐

本文发布于:2023-08-01 04:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1352806.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Python   Profiling   function   called

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!