windows限制:
python 的 time.sleep()方法,在windows操作系统下,最低只能实现到0.001秒,即最少等待1毫秒。
时间单位:
秒(second),时间单位 : s,
毫秒(millisecond),时间单位:ms
微秒(microsecond),时间单位:μs
时间换算:
1s【秒】 = 1000ms【毫秒】
1ms【毫秒】 = 1000μs【微秒】
1μs【微秒】 = 1000ns【纳秒】
1ns 【纳秒】= 1000ps【皮秒】
如何实现微秒μs级等待?
可使用time.perf_counter()方法来实现。
代码如下:
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微秒之间。