小编典典

如何在Python中自动测量函数的执行时间

python

我需要有一个 基类 ,我将使用该 基类 来继承其他类,以评估其功能的执行时间。

因此, 这一翻译的 有这样的事情:

class Worker():
    def doSomething(self):
        start = time.time()
        ... do something
        elapsed = (time.time() - start)
        print "doSomething() took ", elapsed, " time to finish"

#outputs: doSomething() took XX time to finish

我想要这样的东西:

class Worker(BaseClass):
    def doSomething(self):
        ... do something

#outputs the same: doSomething() took XX time to finish

因此,BaseClass需要处理时间测量


阅读 210

收藏
2020-12-20

共1个答案

小编典典

实现此目的的一种方法是使用装饰器
装饰器的PEP)(有关装饰器的一系列教程文章的第一篇)。这是一个可以满足您需求的示例。

from functools import wraps
from time import time

def timed(f):
  @wraps(f)
  def wrapper(*args, **kwds):
    start = time()
    result = f(*args, **kwds)
    elapsed = time() - start
    print "%s took %d time to finish" % (f.__name__, elapsed)
    return result
  return wrapper

这是其用法的一个例子

@timed
def somefunction(countto):
  for i in xrange(countto):
    pass
  return "Done"

为了显示它是如何工作的,我从python提示符下调用了该函数:

>>> timedec.somefunction(10000000)
somefunction took 0 time to finish
'Done'
>>> timedec.somefunction(100000000)
somefunction took 2 time to finish
'Done'
>>> timedec.somefunction(1000000000)
somefunction took 22 time to finish
'Done'
2020-12-20