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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2245161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:09:44  来源:igfitidea点击:

how to measure execution time of functions (automatically) in Python

pythonoop

提问by pars

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

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

So intead ofhaving something like this:

所以而不是有这样的事情:

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

I would like to have something like this:

我想要这样的东西:

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

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

So the BaseClass needs to dealing with measuring time

所以 BaseClass 需要处理测量时间

回答by Geoff Reedy

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.

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

This is an example of its use

这是它的使用示例

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

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

为了展示它是如何工作的,我从 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'

回答by p.marino

Have you checked the "profile" module?

您是否检查过“个人资料”模块

I.e. are you sure you need to implement your own custom framework instead of using the default profiling mechanism for the language?

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

You could also google for "python hotshot" for a similar solution.

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

回答by jathanism

There is also timeit, which is part of the standard library, and is really easy to use. Remember: don't reinvent the wheel!

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