Python cProfile - 被修饰的函数遮挡了性能分析可视化

3

我有一个基类,其中包含一个 @classmethod,它充当许多子类中大量方法的装饰器。

class BaseClass():
    @classmethod
    def some_decorator(cls, method):
        @wraps(method)
        def inner_method(self, *args, **kwargs):
            # do stuff
            return method(self, *args, **kwargs)
        return inner_method


class ChildClass(BaseClass):
    @BaseClass.some_decorator
    def some_child_method(self):
        # do other stuff
        return

当我对这段代码进行分析并通过树形视图查看时,我看到来自数百个不同位置的数千次对“some_decorator”的调用。然后我看到“some_decorator”从刚才来的数百个位置回调。这非常恼人,我还没有找到解决方法,无论是通过更改代码还是以不同的方式进行分析。(目前使用gprof2dot: 如何使用Python性能分析器获取调用树?)你有什么想法吗?

由于装饰器通常为每个被装饰的函数创建一个闭包,所以你是否可以更新(或复制)代码对象并更改文件和行信息以引用装饰函数上方的一行? - Patrick Maupin
1个回答

1

有一些方法可以构建装饰器来保留文档/签名。wrapt库提供了许多相关功能。

https://wrapt.readthedocs.io/en/latest/decorators.html#decorating-class-methods

它最终会看起来像这样:

它会看起来像这样:

class BaseClass():
    @wrapt.decorator
    @classmethod
    def some_decorator(cls, method, instance, *args, *kwargs):
        # do stuff
        return method(instance, *args, **kwargs)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接