在另一个方法中计算python方法调用

时间:2009-08-19 18:19:20

标签: python profiling

我实际上是在尝试用Java做这个,但是我正在自学python的过程中,这让我想知道是否有一个简单/聪明的方法来用包装器做什么。

我想知道在另一个方法中调用特定方法的次数。例如:

def foo(z):
    #do something
    return result

def bar(x,y):
    #complicated algorithm/logic involving foo
    return foobar

因此,对于每次使用各种参数调用bar,我想知道调用foo的次数,也许是这样的输出:

>>> print bar('xyz',3)
foo was called 15 times
[results here]
>>> print bar('stuv',6)
foo was called 23 times
[other results here]

编辑:我意识到我可以在栏内打一个计数器并在我返回时将其转储,但如果有一些魔法可以用包装来完成同样的事情,那将会很酷。这也意味着我可以在其他地方重用相同的包装器,而无需修改方法中的任何代码。

3 个答案:

答案 0 :(得分:20)

听起来几乎就像装饰者的教科书示例一样!

def counted(fn):
    def wrapper(*args, **kwargs):
        wrapper.called += 1
        return fn(*args, **kwargs)
    wrapper.called = 0
    wrapper.__name__ = fn.__name__
    return wrapper

@counted
def foo():
    return

>>> foo()
>>> foo.called
1

你甚至可以使用另一个装饰器来自动记录在另一个函数中调用函数的次数:

def counting(other):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            other.called = 0
            try:
                return fn(*args, **kwargs)
            finally:
                print '%s was called %i times' % (other.__name__, other.called)
        wrapper.__name__ = fn.__name__
        return wrapper
    return decorator

@counting(foo)
def bar():
    foo()
    foo()

>>> bar()
foo was called 2 times

如果foobar最终会自行调用,那么您需要一个更复杂的解决方案来处理堆栈以应对递归。那么你正朝着一个全面的剖析器......

可能这个包装装饰的东西,往往被用于魔术,如果你仍在“自学Python”,它不是一个理想的地方!

答案 1 :(得分:7)

这定义了一个装饰器:

def count_calls(fn):
    def _counting(*args, **kwargs):
        _counting.calls += 1
        return fn(*args, **kwargs)
    _counting.calls = 0
    return _counting

@count_calls
def foo(x):
    return x

def bar(y):
    foo(y)
    foo(y)

bar(1)
print foo.calls

答案 2 :(得分:2)

回复之后 - 这是装饰工厂的一种方式......

import inspect

def make_decorators():
    # Mutable shared storage...
    caller_L = []
    callee_L = []
    called_count = [0]
    def caller_decorator(caller):
        caller_L.append(caller)
        def counting_caller(*args, **kwargs):
            # Returning result here separate from the count report in case
            # the result needs to be used...
            result = caller(*args, **kwargs)
            print callee_L[0].__name__, \
                   'was called', called_count[0], 'times'
            called_count[0] = 0
            return result
        return counting_caller

    def callee_decorator(callee):
        callee_L.append(callee)
        def counting_callee(*args, **kwargs):
            # Next two lines are an alternative to
            # sys._getframe(1).f_code.co_name mentioned by Ned...
            current_frame = inspect.currentframe()
            caller_name = inspect.getouterframes(current_frame)[1][3]
            if caller_name == caller_L[0].__name__:
                called_count[0] += 1
            return callee(*args, **kwargs)
        return counting_callee

    return caller_decorator, callee_decorator

caller_decorator, callee_decorator = make_decorators()

@callee_decorator
def foo(z):
    #do something
    return ' foo result'

@caller_decorator
def bar(x,y):
    # complicated algorithm/logic simulation...
    for i in xrange(x+y):
        foo(i)
    foobar = 'some result other than the call count that you might use'
    return foobar


bar(1,1)
bar(1,2)
bar(2,2)

这是输出(用Python 2.5.2测试):

foo was called 2 times
foo was called 3 times
foo was called 4 times
相关问题