您好,登錄后才能下訂單哦!
本篇內容主要講解“python計算函數(shù)執(zhí)行時長的方法是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“python計算函數(shù)執(zhí)行時長的方法是什么”吧!
python開發(fā),有時需要做性能分析及性能優(yōu)化,這時就需要記錄一些耗時函數(shù)執(zhí)行時間問題,然后針對函數(shù)邏輯進行優(yōu)化。
在python3中一般都有哪些方法呢。
這種方法較簡單,但如果想更精確的計算函數(shù)的執(zhí)行時間,會產生精度缺失,沒辦法統(tǒng)計時間極短的函數(shù)耗時。
import time
def func():
time.sleep(1)
t = time.time()
func()
print(f'耗時:{time.time() - t:.4f}s')
耗時:1.0050s
perf_counter是在python3.3新添加的,返回性能計數(shù)器的值,返回值是浮點型,統(tǒng)計結果包括睡眠的時間,單個函數(shù)的返回值無意義,只有多次運行取差值的結果才是有效的函數(shù)執(zhí)行時間。
import time
def func():
print('hello world')
t = time.perf_counter()
func()
print(f'耗時:{time.perf_counter() - t:.8f}s')
hello world
耗時:0.00051790s
timeit()函數(shù)有5個參數(shù):
stmt 參數(shù)是需要執(zhí)行的語句,默認為 pass
setup 參數(shù)是用來執(zhí)行初始化代碼或構建環(huán)境的語句,默認為 pass
timer 是計時器,默認是 perf_counter()
number 是執(zhí)行次數(shù),默認為一百萬
globals 用來指定要運行代碼的命名空間,默認為 None
import timeit
def func():
print('hello world')
print(f'耗時: {timeit.timeit(stmt=func, number=1)}')
hello world
耗時: 0.0007705999999999824
在實際項目代碼中,可以通過裝飾器方便的統(tǒng)計函數(shù)運行耗時。使用裝飾器來統(tǒng)計函數(shù)執(zhí)行耗時的好處是對函數(shù)的入侵性小,易于編寫和修改。
裝飾器裝飾函數(shù)的方案只適用于統(tǒng)計函數(shù)的運行耗時,如果有代碼塊耗時統(tǒng)計的需求就不能用了,這種情況下可以使用 with 語句自動管理上下文。
import time
def coast_time(func):
def fun(*args, **kwargs):
t = time.perf_counter()
result = func(*args, **kwargs)
print(f'函數(shù):{func.__name__} 耗時:{time.perf_counter() - t:.8f} s')
return result
return fun
@coast_time
def test():
print('hello world')
if __name__ == '__main__':
test()
import asyncio
import time
from asyncio.coroutines import iscoroutinefunction
def coast_time(func):
def fun(*args, **kwargs):
t = time.perf_counter()
result = func(*args, **kwargs)
print(f'函數(shù):{func.__name__} 耗時:{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'函數(shù):{func.__name__} 耗時:{time.perf_counter() - t:.8f} s')
return result
if iscoroutinefunction(func):
return func_async
else:
return fun
@coast_time
def test():
print('hello test')
time.sleep(1)
@coast_time
async def test_async():
print('hello test_async')
await asyncio.sleep(1)
if __name__ == '__main__':
test()
asyncio.get_event_loop().run_until_complete(test_async())
hello test
函數(shù):test 耗時:1.00230700 s
hello test_async
函數(shù):test_async 耗時:1.00572550 s
通過實現(xiàn) enter 和 exit 函數(shù)可以在進入和退出上下文時進行一些自定義動作,例如連接或斷開數(shù)據(jù)庫、打開或 關閉文件、記錄開始或結束時間等,例如:我們用來統(tǒng)計函數(shù)塊的執(zhí)行時間。
with語句不僅可以統(tǒng)計代碼塊的執(zhí)行時間,也可以統(tǒng)計函數(shù)的執(zhí)行時間,還可以統(tǒng)計多個函數(shù)的執(zhí)行時間之和,相比裝飾器來說對代碼的入侵性比較大,不易于修改,好處是使用起來比較靈活,不用寫過多的重復代碼。
import asyncio
import time
class CoastTime(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'耗時:{time.perf_counter() - self.t:.8f} s')
def test():
print('hello test')
with CoastTime():
time.sleep(1)
async def test_async():
print('hello test_async')
with CoastTime():
await asyncio.sleep(1)
if __name__ == '__main__':
test()
asyncio.get_event_loop().run_until_complete(test_async())
hello test
耗時:1.00723310 s
hello test_async
耗時:1.00366820 s
到此,相信大家對“python計算函數(shù)執(zhí)行時長的方法是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。