【问题标题】:how to measure execution time of functions (automatically) in Python如何在 Python 中(自动)测量函数的执行时间
【发布时间】:2010-02-11 14:44:40
【问题描述】:

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

所以而不是有这样的东西:

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

【问题讨论】:

  • 我建议使用类装饰器,而不是在 BaseClass 中实现计时。
  • 当你想知道时间的时候,为什么不直接使用像 cProfiler 这样的分析器呢?
  • @Justin cProfiler 很好,但我需要知道每次报告它们的时间。

标签: python oop


【解决方案1】:

一种方法是使用装饰器(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'

【讨论】:

  • 感谢您的精彩回答!这正是我想要的。
  • 简洁代码的好例子,展示了装饰器是 Python 中最好的乐趣之一
  • @ronnieaka 我只是模块名称。我在timedec.py中写了timedsomefunction的定义,并从解释器中导入来测试它们。
  • 好东西。谢谢你。与他人分享的一件事。以毫秒为单位测量执行时间更有意义。例如杰夫的回答对我有用,但我只看到以下内容。 abc_function took 0 time to finish。此更改会将时间转换为毫秒print "%s took %d milliSeconds to finish" % (f.__name__, elapsed*1000)
【解决方案2】:

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

【讨论】:

  • 确实非常简单好用!
  • 时间看来很有希望!我会将它与 Geoff 的解决方案结合起来。
【解决方案3】:

您检查过"profile" module吗?

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

您也可以在 Google 上搜索“python hotshot”以获得类似的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 2023-03-09
    相关资源
    最近更新 更多