检查函数是否被调用了x个时间量

时间:2014-03-19 15:02:13

标签: python function call time-frequency

我没有在任何地方找到这样的问题所以我会在这里问一下。

如何检查我写的某些特定函数是否在一段时间内没有被调用?

3 个答案:

答案 0 :(得分:2)

您可以在函数定义中嵌入最后一个调用时间:

def myfun():
  myfun.last_called = datetime.now()
  # … do things

从这一点开始,应该很容易判断函数何时被调用。每次调用它都会更新其last_called时间戳。

更通用的方法是定义一个函数装饰器来附加属性:

def remembercalltimes(f, *args, **kwargs):
    """A decorator to help a function remember when it was last called."""
    def inner(*args, **kwargs):
        inner.last_called = datetime.now()
        return f(*args, **kwargs)
    return inner

@remembercalltimes
def myfun():
    # … do things

>>> myfun()
>>> myfun.last_called
>>> datetime.datetime(2014, 3, 19, 11, 47, 5, 784833)

答案 1 :(得分:0)

import time
last_time_f_called = time.time()

def f():
  global last_time_f_called
  now = time.time()
  time_since = now - last_time_f_called
  last_time_f_called = now
  # do whatever you wanted to do about value of time_since

那样的东西?

你可以将它包装在装饰器中,它在dict中更新时间,其中key是函数名称,如果它是你想要做的很多事情......

答案 2 :(得分:0)

这似乎是在函数__dict__中填充该信息的合理时间,可能是装饰者。

def lastcalled(func):
    def inner():
        from datetime import datetime
        then = func.__dict__.get('lastcalled')
        diff = int((datetime.now() - then ).total_seconds()) if then else None
        print('Last called: {}'.format('{} sec ago'.format(diff) if diff else 'Never'))
        func()
        func.lastcalled = datetime.now()
    return inner

演示:

@lastcalled
def f():
    print('printing in f()')

f()
Last called: Never 
printing in f()

#wait 5 seconds

f()
Last called: 5 sec ago
printing in f()