如何查找python中任何函数或任何例程的总耗用时间

时间:2017-06-13 15:17:23

标签: python function time elapsed

目前我正在使用以下代码查找我手动使用所有开始时间和结束时间的任何例程/函数的已用时间

但是,我想要一个功能应该自动返回整个函数需要多长时间,就好像我们运行查询时它用​​来说多少秒和毫秒就像我想要运行任何函数,每个函数应该返回我那个经过的时间。

这是我的代码,我绝对不满意这一点,我想要一个高端的专业代码行帮助。感谢。

def ElaspedTime(stime,etime):
    from datetime import timedelta
    timediff = timedelta(seconds=etime - stime)
    return timediff

def STime():
    return time.monotonic()

def ETime():
    return time.monotonic()

#start_time = time.monotonic()

##call functions here

#end_time = time.monotonic()

#print( ElaspedTime(start_time,end_time))

2 个答案:

答案 0 :(得分:0)

您可以创建这样的包装函数:

def runWithTime(f,*args):
    from datetime import timedelta
    import time
    stime = time.time()
    r = f(*args)
    etime = time.time()
    timediff = timedelta(etime - stime)
    print timediff
    return r

def a(x,y):
    return x+y

r = runWithTime(a,1,2)
print r

答案 1 :(得分:0)

写一个装饰器如下(用print替换log.debug ...):

from functools import wraps
def with_stopwatch(f):
    @wraps(f)
    def wrapped(*args, **kw):
        tstart = time()
        result = f(*args, **kw)
        tend = time()
        log.debug('>>> func:%r took: %2.4f sec' % (f.__name__, tend - tstart))
        return result
    return wrapped

@with_stopwatch
def function()
    ...
相关问题