如何在Python中自动测量函数的执行时间 [英] how to measure execution time of functions (automatically) in Python

查看:116
本文介绍了如何在Python中自动测量函数的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有一个基类,我将使用该基类继承其他我要测量其功能执行时间的类.

I need to have a base class which I will use to inherit other classes which I would like to measure execution time of its functions.

所以感兴趣的有这样的东西:

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

So the BaseClass needs to dealing with measuring time

推荐答案

一种方法是使用装饰器(第一个一系列有关装饰器的教程文章).这是一个满足您需求的示例.

One way to do this would be with a decorator (PEP for decorators) (first of a series of tutorial articles on decorators). Here's an example that does what you want.

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提示符下调用了该函数:

To show how it works I called the function from the python prompt:

>>> 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中自动测量函数的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆