python實現(xiàn)微秒級等待問題(windows)
更新時間:2024年06月24日 09:08:04 作者:霸蠻哥
這篇文章主要介紹了python實現(xiàn)微秒級等待問題(windows),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
python實現(xiàn)微秒級等待
windows限制
python 的 time.sleep()方法,在windows操作系統(tǒng)下,最低只能實現(xiàn)到0.001秒,即最少等待1毫秒。
時間單位
- 秒(second),時間單位 : s,
- 毫秒(millisecond),時間單位:ms
- 微秒(microsecond),時間單位:μs
時間換算:
- 1s【秒】 = 1000ms【毫秒】
- 1ms【毫秒】 = 1000μs【微秒】
- 1μs【微秒】 = 1000ns【納秒】
- 1ns 【納秒】= 1000ps【皮秒】
如何實現(xiàn)微秒μs級等待?
可使用time.perf_counter()方法來實現(xiàn)。
代碼如下:
import time
def microsecond_sleep(sleep_time):
"""微秒等待
:param sleep_time: int, 微秒
:return:
"""
end_time = time.perf_counter() + (sleep_time - 0.8) / 1e6 # 0.8是時間補償,需要根據自己PC的性能去實測
while time.perf_counter() < end_time:
pass
start = time.perf_counter()
microsecond_sleep(10) # 等待10微秒
end = time.perf_counter()
print(start)
print(end)
print("等待時間:", (end-start) * 1e6, "微秒")運行結果如下:
1040204.7426661
1040204.742676
等待時間: 9.899958968162537 微秒
多次測試,實際消耗時間在9.89-10.30微秒之間。
python編程,毫秒級延時的一種實現(xiàn)
linux適用
import time # 導入time模塊
def delayMicrosecond(t): # 微秒級延時函數(shù)
start,end=0,0 # 聲明變量
start=time.time() # 記錄開始時間
t=(t-3)/1000000 # 將輸入t的單位轉換為秒,-3是時間補償
while end-start<t: # 循環(huán)至時間差值大于或等于設定值時
end=time.time() # 記錄結束時間
a=time.time() # 記錄延時函數(shù)開始執(zhí)行時的時間
delayMicrosecond(10) #延時 35 微秒
b=time.time() # 記錄延時函數(shù)結束時的時間
print((b))
print((a))
print((b-a)*1000000)windows適用
import time # 導入time模塊
def procedure():
time.sleep(2.5)
# measure process time
t0 = time.process_time()
procedure()
print (time.process_time() - t0, "seconds process time")
# measure wall time
t0 = time.time()
procedure()
print (time.time() - t0, "seconds wall time")總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
基于Python實現(xiàn)簡單的人臉識別系統(tǒng)
這篇文章主要介紹了如何通過Python實現(xiàn)一個簡單的人臉識別系統(tǒng),文中的示例代碼講解詳細,對我們學習Python有一定的幫助,感興趣的可以跟隨小編一起試一試2022-01-01

