簡體   English   中英

如何在python中查找任何函數或任何例程的總經過時間

[英]How to Find the total elapsed time for any function or any routine in python

目前,我正在使用下面的代碼來查找我手動使用開始時間和結束時間的所有例程/功能的經過時間

但是,我希望功能可以自動返回整個函數,花費了多少時間,好像我們在運行查詢時一樣,它用來表示我想運行任何函數的秒數和毫秒數,而每個函數都應該返回過去的時間時間。

這是我的代碼,對此我絕對不滿意,我需要高端專業代碼行的幫助。 謝謝。

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))

您可以創建一個包裝函數,如下所示:

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

編寫一個裝飾器,如下所示(將log.debug替換為print ...):

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()
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM