跳转到主要内容

带有日志支持的简单基于上下文的性能分析

项目描述

easyprofile — Python的简单基于上下文的性能分析

easyprofile包提供了在本地上下文中设置Python的sys.setprofile()的功能,以及一系列辅助工具来自动化性能分析和日志记录。

安装

使用pip按常规方式安装

pip install easyprofile

用法

替换本地sys.setprofile()

如果您希望在本地上下文中安装一个原本会传递给sys.setprofile()的性能函数,请使用easyprofile.profile上下文管理器

>>> import easyprofile
>>>
>>> # profile function of the sys.setprofile() form
>>> def myfunc(frame, event, arg):
...     print('profile:', event)
...
>>> # a test function to be profiled
>>> def profile_this(n):
...     # this inner function call will not show in the profile
...     return sum(range(n))
...
>>> # replace the profile function locally
>>> with easyprofile.profile(myfunc):
...     # only this call will be profiled
...     profile_this(100_000_000)
...
profile: call
profile: return
4999999950000000

忽略调用

如果您希望在本地忽略一些调用,可以使用easyprofile.ignore上下文管理器

>>> with easyprofile.profile(myfunc):
...     # this call will be profiled
...     profile_this(100_000_000)
...
...     with easyprofile.ignore:
...         # this call will be ignored
...         profile_this(100)
...
profile: call
profile: return
4999999950000000
4950

上下文管理器通过暂时将sys.setprofile()设置为None来实现,因此与任何性能分析器都兼容。

请注意,easyprofile.ignore不是一个可调用的对象!

标记函数为忽略

可以使用@easyprofile.ignored装饰器将函数标记为始终忽略

>>> # this function is ignored by easyprofile
>>> @easyprofile.ignored
... def ignored_func():
...     return 42
...
>>> with easyprofile.profile(myfunc):
...     ignored_func()
...
42

请注意,与easyprofile.ignore上下文管理器不同,装饰器只与easyprofile一起使用。

基于类的性能分析器

为了便于创建自定义性能分析器,easyprofile.BaseProfile类提供了一个基于方法的事件处理接口。当遇到事件<event>时,会调用名称为_<event>(即下划线—事件名称)的方法,带有签名frame, arg

>>> class MyProfile(easyprofile.BaseProfile):
...     def __init__(self, arg, *, kwarg):
...         print(f'MyProfile: init, {arg=}, {kwarg=}')
...
...     def _attach(self, frame, arg):
...         print('MyProfile: attached')
...
...     def _detach(self, frame, arg):
...         print('MyProfile: detached')
...
...     def _call(self, frame, arg):
...         print('MyProfile: function called')
...
...     def _return(self, frame, arg):
...         print('MyProfile: function returned')
...
...     # profile C extension calls using the same methods
...     _c_call = _call
...     _c_return = _return
...

基于类的性能分析器可以通过其profile()类方法轻松调用,该方法将其参数传递给构造函数

>>> # use the MyProfile class for local profiling
>>> with MyProfile.profile('hello', kwarg='world'):
...     profile_this(100_000_000)
...
MyProfile: init, arg='hello', kwarg='world'
MyProfile: function called
MyProfile: function returned
4999999950000000

项目详情


下载文件

下载适合您平台的应用程序。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码发行版

easyprofile-0.1.5.tar.gz (4.0 kB 查看哈希值)

上传于 源代码

构建发行版

easyprofile-0.1.5-py3-none-any.whl (4.5 kB 查看哈希值)

上传于 Python 3

由以下组织支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误记录StatusPageStatusPage状态页面