计算调用函数或变量的次数

2024-04-25 15:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从用python编写的现有代码中获取每个函数或变量的调用次数。在

我的想法是重写对象的getattribute函数,如下所示:

acc = {}

class object(object):
    def __getattribute__(self, p):
        acc.update({str(self) + p: acc.get(str(self) + p, 0) + 1})
        return supe(object, self).__getattribute__(p)

class A(object):
    def a(self):
        pass

class B(A):
    def b(self):
        pass

def main():
    a = A()
    a.a()
    b = B()
    b.b()
    b.a = 'a'
    b.a

    print acc
if __name__ == '__main__':
    main()

但是,它只能计算对象中的函数和变量,如何计算普通函数或变量,例如:

^{pr2}$

我想得到的结果是2,有什么工具或方法可以做到吗?在

对不起,我的台球英语,我真正需要的是调用时间,而不是运行时间。 如上所述,fun1()被调用了两次。在


Tags: 对象函数代码selfobjectmaindef时间
2条回答

使用decorator。在

>>> def timestamp(container, get_timestamp):
...      def timestamp_decorator(func):
...          def decorated(*args, **kwargs):
...              container[func.func_name] = get_timestamp()
...              return func(*args, **kwargs)
...          return decorated
...      return timestamp_decorator
... 

你就这样使用它:

^{pr2}$

有一种方法可以为一个函数创建一个计数器decorator(nbot-timestamp decorator),并使用这个decorator自动将所有函数包装在给定的模块中-

因此,如果要计算函数调用的模块名为“mymodule”,则可以编写:

class function_counter(object):
    def __init__(self, func):
        self.counter = 0
        self.func = func

    def __call__(self, *args, **kw):
        self.counter += 1
        return self.func(*args, **kw)

以及:

^{pr2}$

要将此应用于模块中的所有函数,可以编写如下内容:

import mymodule
from types import FunctionType, BuiltinFunctionType
# define the "function_counter" class as above here (or import it)

for key, value in mymodule.__dict__.items():
    if isinstance(value, (FunctionType, BuiltinFunctionType)):
        mymodule.__dict__[key] = function_counter(value)

这对于计算函数的使用情况是一样的。 但是,如果你想计算模块级变量的使用量,那就不那么容易了 不能像在示例中为类重写从模块对象检索的机制属性。在

这样做的方法是,在导入模块后,用模块替换一个类(该类实现了您在示例中所做的属性计数方案),并将所有模块属性分配给该类中的实例属性。在

这不是一个经过测试的示例(与上面的示例不同),但请尝试以下方法:

import mymodule

from types import FunctionType

class Counter(object):
   # counter __getattribute__ just as you did above

c = Counter()
for key, value in mymodule.__dict__.items():
    setattr(c, key, staticmethod(value) if isinstance(value, FunctionType) else value)
mymodule = c

相关问题 更多 >