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

时间:2010-02-11 14:44:41

标签: python oop

我需要一个基类,我将用它来继承我想测量其函数执行时间的其他类。

intead of 有这样的东西:

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需要处理测量时间

3 个答案:

答案 0 :(得分:49)

一种方法是使用装饰器(PEP for decorators) (first of a series of tutorial articles on decorators)。这是一个做你想做的事的例子。

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'

答案 1 :(得分:10)

您是否检查了 "profile" module

即。您确定需要实现自己的自定义框架,而不是使用该语言的默认分析机制吗?

你也可以谷歌为“python hotshot”获得类似的解决方案。

答案 2 :(得分:6)

还有timeit,它是标准库的一部分,并且非常易于使用。记住:不要重新发明轮子!