
sleep()
sleep(secs) 將執行中的 thread 暫停給定的秒數 secs。通常用於模擬延遲、建立暫停或間隔 requests。 secs 可以是 float 以指示更精確的睡眠時間。
範例
有時,API 在一定時間內可以發送的 requests 數量有限制。在這種情況下,您可能需要等待才能發出另一個請求,以避免達到速率限制。
import requests
import time
for i in range(10):
response = requests.get('http://example.com')
print(response.status_code)
time.sleep(1) # Wait for 1 second before the next request執行結果:
範例 – 倒數計時器
範例 – 測量函數的性能
測量函數的性能 – Pythonic
測量函數的性能 – 遞迴 ver.
_is_recursive_call 預設為 False,因此對於頂層調用 (直接進行的調用),將設置開始和結束時間並打印執行時間。 對於遞迴調用,_is_recursive_call=True,因此不會設置開始和結束時間,也不會打印執行時間。
範例 – debugging
詳見: functools【可調用物件】
執行結果:
參考資料
time — Time access and conversions — Python 3.11.4 documentation
「耗時測試」python time包中的time()和process_time()如何選擇? - 資訊咖
Python 中的定時器函式 | D棧 - Delft Stack
Last updated
Was this helpful?