計算函數(shù)執(zhí)行時長的方法
python開發(fā),有時需要做性能分析及性能優(yōu)化,這時就需要記錄一些耗時函數(shù)執(zhí)行時間問題,然后針對函數(shù)邏輯進行優(yōu)化。
在python3中一般都有哪些方法呢。
1、使用time.time()
這種方法較簡單,但如果想更精確的計算函數(shù)的執(zhí)行時間,會產(chǎn)生精度缺失,沒辦法統(tǒng)計時間極短的函數(shù)耗時。
import time
def func():
time.sleep(1)
t = time.time()
func()
print(f'耗時:{time.time() - t:.4f}s')
耗時:1.0050s
2、使用time.perf_counter()
perf_counter是在python3.3新添加的,返回性能計數(shù)器的值,返回值是浮點型,統(tǒng)計結(jié)果包括睡眠的時間,單個函數(shù)的返回值無意義,只有多次運行取差值的結(jié)果才是有效的函數(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
3、使用timeit.timeit ()
timeit()函數(shù)有5個參數(shù):
stmt 參數(shù)是需要執(zhí)行的語句,默認為 pass
setup 參數(shù)是用來執(zhí)行初始化代碼或構(gòu)建環(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
4、使用裝飾器統(tǒng)計
在實際項目代碼中,可以通過裝飾器方便的統(tǒng)計函數(shù)運行耗時。使用裝飾器來統(tǒng)計函數(shù)執(zhí)行耗時的好處是對函數(shù)的入侵性小,易于編寫和修改。
裝飾器裝飾函數(shù)的方案只適用于統(tǒng)計函數(shù)的運行耗時,如果有代碼塊耗時統(tǒng)計的需求就不能用了,這種情況下可以使用 with 語句自動管理上下文。
(1)同步函數(shù)的統(tǒng)計
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
def test():
print('hello world')
if __name__ == '__main__':
test()
(2)異步函數(shù)的統(tǒng)計
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
def test():
print('hello test')
time.sleep(1)
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
5、with語句統(tǒng)計
通過實現(xiàn) enter 和 exit 函數(shù)可以在進入和退出上下文時進行一些自定義動作,例如連接或斷開數(shù)據(jù)庫、打開或 關(guān)閉文件、記錄開始或結(jié)束時間等,例如:我們用來統(tǒng)計函數(shù)塊的執(zhí)行時間。
with語句不僅可以統(tǒng)計代碼塊的執(zhí)行時間,也可以統(tǒng)計函數(shù)的執(zhí)行時間,還可以統(tǒng)計多個函數(shù)的執(zhí)行時間之和,相比裝飾器來說對代碼的入侵性比較大,不易于修改,好處是使用起來比較靈活,不用寫過多的重復(fù)代碼。
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