Python中計(jì)算函數(shù)執(zhí)行時間的五種方法
1. time.time()
在計(jì)算函數(shù)執(zhí)行時間時,這種時最簡潔的一種方式,用兩個時間戳做減法。
import time
def func():
print('func start')
time.sleep(1)
print('func end')
t = time.time()
func()
print(f'coast:{time.time() - t:.4f}s')
結(jié)果為:
func start
func end
coast:1.0003s
這種方法很簡單,也很常用,但是如果想更精確的計(jì)算函數(shù)的執(zhí)行時間,就會產(chǎn)生精度缺失。
2. time.perf_counter() 推薦
示例一中注釋掉time.sleep(1),只統(tǒng)計(jì)兩個 print 函數(shù)的執(zhí)行時間:
import time
def func():
print('func start')
# time.sleep(1)
print('func end')
t = time.time()
func()
print(f'coast:{time.time() - t:.8f}s')輸出:
func start
func end
coast:0.0000s
這就說明time.time() 函數(shù)的精度不是特別高,沒法統(tǒng)計(jì)執(zhí)行時間極短的函數(shù)耗時。
perf_counter 函數(shù)是在 python3.3 中新添加的,它返回性能計(jì)數(shù)器的值,返回值是浮點(diǎn)型,統(tǒng)計(jì)結(jié)果包括睡眠的時間,單個函數(shù)的返回值無意義,只有多次運(yùn)行取差值的結(jié)果才是有效的函數(shù)執(zhí)行時間。
import time
def func():
print('func start')
# time.sleep(1)
print('func end')
t = time.perf_counter()
func()
print(f'coast:{time.perf_counter() - t:.8f}s')結(jié)果
func start
func end
coast:0.00001500s
結(jié)果并不是 0 秒, 而是一個很小的值,這說明 perf_counter() 函數(shù)可以統(tǒng)計(jì)出 print 函數(shù)的執(zhí)行耗時,并且統(tǒng)計(jì)精度要比 time.time() 函數(shù)要高,比較推薦作為計(jì)時器來使用。
3. timeit.timeit ()
timeit() 函數(shù)有 5 個參數(shù),stmt=‘pass’, setup=‘pass’, timer=, number=1000000, globals=None。
- stmt 參數(shù)是需要執(zhí)行的語句,默認(rèn)為 pass
- setup 參數(shù)是用來執(zhí)行初始化代碼或構(gòu)建環(huán)境的語句,默認(rèn)為 pass
- timer 是計(jì)時器,默認(rèn)是 perf_counter()
- number 是執(zhí)行次數(shù),默認(rèn)為一百萬
- globals 用來指定要運(yùn)行代碼的命名空間,默認(rèn)為 None。
import time
import timeit
def func():
print('func start')
time.sleep(1)
print('func end')
print(timeit.timeit(stmt=func, number=1))
以上方案中比較推薦使用的是 time.perf_counter() 函數(shù),它具有比較高的精度,同時還被用作 timeit 函數(shù)默認(rèn)的計(jì)時器。
4.裝飾器統(tǒng)計(jì)運(yùn)行耗時
在實(shí)際項(xiàng)目代碼中,可以通過裝飾器方便的統(tǒng)計(jì)函數(shù)運(yùn)行耗時。
import time
def cost_time(func):
def fun(*args, **kwargs):
t = time.perf_counter()
result = func(*args, **kwargs)
print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
return result
return fun
@cost_time
def test():
print('func start')
time.sleep(2)
print('func end')
if __name__ == '__main__':
test()
如果有使用異步函數(shù)的需求也可以加上:
import asyncio
import time
from asyncio.coroutines import iscoroutinefunction
def cost_time(func):
def fun(*args, **kwargs):
t = time.perf_counter()
result = func(*args, **kwargs)
print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
return result
async def func_async(*args, **kwargs):
t = time.perf_counter()
result = await func(*args, **kwargs)
print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
return result
if iscoroutinefunction(func):
return func_async
else:
return fun
@cost_time
def test():
print('func start')
time.sleep(2)
print('func end')
@cost_time
async def test_async():
print('async func start')
await asyncio.sleep(2)
print('async func end')
if __name__ == '__main__':
test()
asyncio.get_event_loop().run_until_complete(test_async())
使用裝飾器來統(tǒng)計(jì)函數(shù)執(zhí)行耗時的好處是對函數(shù)的入侵性小,易于編寫和修改。
裝飾器裝飾函數(shù)的方案只適用于統(tǒng)計(jì)函數(shù)的運(yùn)行耗時,如果有代碼塊耗時統(tǒng)計(jì)的需求就不能用了,這種情況下我們可以使用 with 語句自動管理上下文。
5. with 語句統(tǒng)計(jì)運(yùn)行耗時
通過實(shí)現(xiàn) enter 和 exit 函數(shù)可以讓我們在進(jìn)入上下文和退出上下文時進(jìn)行一些自定義動作,例如連接 / 斷開數(shù)據(jù)庫、打開 / 關(guān)閉文件、記錄開始 / 結(jié)束時間等等,這里我們用來統(tǒng)計(jì)函數(shù)塊的執(zhí)行時間。
import asyncio
import time
class CostTime(object):
def __init__(self):
self.t = 0
def __enter__(self):
self.t = time.perf_counter()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f'cost time:{time.perf_counter() - self.t:.8f} s')
def test():
print('func start')
with CostTime():
time.sleep(2)
print('func end')
async def test_async():
print('async func start')
with CostTime():
await asyncio.sleep(2)
print('async func end')
if __name__ == '__main__':
test()
asyncio.get_event_loop().run_until_complete(test_async())
with 語句不僅可以統(tǒng)計(jì)代碼塊的執(zhí)行時間,也可以統(tǒng)計(jì)函數(shù)的執(zhí)行時間,還可以統(tǒng)計(jì)多個函數(shù)的執(zhí)行時間之和,相比裝飾器來說對代碼的入侵性比較大,不易于修改,好處是使用起來比較靈活,不用寫過多的重復(fù)代碼。
6.延展:python實(shí)現(xiàn)函數(shù)超時退出
方法一
import time
import eventlet#導(dǎo)入eventlet這個模塊
eventlet.monkey_patch()#必須加這條代碼
with eventlet.Timeout(5,False):#設(shè)置超時時間為2秒
time.sleep(4)
print('沒有跳過這條輸出')
print('跳過了輸出')
第二個方法 不太會用,用的不成功,不如第一個
import time
import timeout_decorator
@timeout_decorator.timeout(5)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
Python設(shè)置函數(shù)調(diào)用超時
import time import signal def test(i): time.sleep(i%4) print "%d within time"%(i) return i if __name__ == '__main__': def handler(signum, frame): raise AssertionError i = 0 for i in range(1,10): try: signal.signal(signal.SIGALRM, handler) signal.alarm(3) test(i) i = i + 1 signal.alarm(0) except AssertionError: print "%d timeout"%(i)
說明:
1、調(diào)用test函數(shù)超時監(jiān)控,使用sleep模擬函數(shù)執(zhí)行超時
2、引入signal模塊,設(shè)置handler捕獲超時信息,返回?cái)嘌藻e誤
3、alarm(3),設(shè)置3秒鬧鐘,函數(shù)調(diào)用超時3秒則直接返回
4、捕獲異常,打印超時信息
執(zhí)行結(jié)果
within time
within time
timeout
within time
within time
within time
timeout
within time
within time
到此這篇關(guān)于Python中計(jì)算函數(shù)執(zhí)行時間的五種方法的文章就介紹到這了,更多相關(guān)Python計(jì)算函數(shù)執(zhí)行時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python運(yùn)行cmd命令10種方式并獲得返回值的高級技巧
這篇文章主要給大家介紹了關(guān)于python運(yùn)行cmd命令10種方式并獲得返回值的高級技巧,主要包括python腳本執(zhí)行CMD命令并返回結(jié)果的例子使用實(shí)例、應(yīng)用技巧,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
回歸預(yù)測分析python數(shù)據(jù)化運(yùn)營線性回歸總結(jié)
本文主要介紹了python數(shù)據(jù)化運(yùn)營中的線性回歸一般應(yīng)用場景,常用方法,回歸實(shí)現(xiàn),回歸評估指標(biāo),效果可視化等,并采用了回歸預(yù)測分析的數(shù)據(jù)預(yù)測方法2021-08-08
OpenCV+face++實(shí)現(xiàn)實(shí)時人臉識別解鎖功能
這篇文章主要為大家詳細(xì)介紹了OpenCV+face++實(shí)現(xiàn)實(shí)時人臉識別解鎖功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08
Ubuntu中安裝指定Python版本方法詳解(理論上各版本通用)
現(xiàn)在基于linux的發(fā)行版本有很多,有centos,ubuntu等,一般基于linux的衍生系統(tǒng)至少都安裝了Python2版本,但是現(xiàn)在Python已經(jīng)是3.x版本大行其道了,這篇文章主要給大家介紹了關(guān)于Ubuntu中安裝指定Python版本方法的相關(guān)資料,理論上各版本通用,需要的朋友可以參考下2023-06-06
Python簡直是萬能的,這5大主要用途你一定要知道?。ㄍ扑])
這篇文章主要介紹了Python主要用途,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
python實(shí)現(xiàn)炫酷屏幕保護(hù)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)炫酷屏幕保護(hù)效果,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以跟隨小編一起了解一下2023-12-12

