tft每日頭條

 > 生活

 > 測量程序中某個函數的執行時間

測量程序中某個函數的執行時間

生活 更新时间:2024-08-14 15:12:12

測量程序中某個函數的執行時間(計算函數執行時長的方法)1

python開發,有時需要做性能分析及性能優化,這時就需要記錄一些耗時函數執行時間問題,然後針對函數邏輯進行優化。

在python3中一般都有哪些方法呢。

1. 使用time.time()

這種方法較簡單,但如果想更精确的計算函數的執行時間,會産生精度缺失,沒辦法統計時間極短的函數耗時。

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新添加的,返回性能計數器的值,返回值是浮點型,統計結果包括睡眠的時間,單個函數的返回值無意義,隻有多次運行取差值的結果才是有效的函數執行時間。

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()函數有5個參數: stmt 參數是需要執行的語句,默認為 pass setup 參數是用來執行初始化代碼或構建環境的語句,默認為 pass timer 是計時器,默認是 perf_counter() number 是執行次數,默認為一百萬 globals 用來指定要運行代碼的命名空間,默認為 None import timeit def func(): print('hello world') print(f'耗時: {timeit.timeit(stmt=func, number=1)}') hello world 耗時: 0.0007705999999999824

4. 使用裝飾器統計

在實際項目代碼中,可以通過裝飾器方便的統計函數運行耗時。使用裝飾器來統計函數執行耗時的好處是對函數的入侵性小,易于編寫和修改。

裝飾器裝飾函數的方案隻适用于統計函數的運行耗時,如果有代碼塊耗時統計的需求就不能用了,這種情況下可以使用 with 語句自動管理上下文。

4.1 同步函數的統計

import time def coast_time(func): def fun(*args, **kwargs): t = time.perf_counter() result = func(*args, **kwargs) print(f'函數:{func.__name__} 耗時:{time.perf_counter() - t:.8f} s') return result return fun @coast_time def test(): print('hello world') if __name__ == '__main__': test()

4.2 異步函數的統計

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'函數:{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'函數:{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 函數:test 耗時:1.00230700 s hello test_async 函數:test_async 耗時:1.00572550 s

5. with語句統計

通過實現 enterexit 函數可以在進入和退出上下文時進行一些自定義動作,例如連接或斷開數據庫、打開或 關閉文件、記錄開始或結束時間等,例如:我們用來統計函數塊的執行時間。

with語句不僅可以統計代碼塊的執行時間,也可以統計函數的執行時間,還可以統計多個函數的執行時間之和,相比裝飾器來說對代碼的入侵性比較大,不易于修改,好處是使用起來比較靈活,不用寫過多的重複代碼。

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

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved