python实现微秒级等待问题(windows)
作者:霸蛮哥
这篇文章主要介绍了python实现微秒级等待问题(windows),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
python实现微秒级等待
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微秒之间。
python编程,毫秒级延时的一种实现
linux适用
import time # 导入time模块
def delayMicrosecond(t): # 微秒级延时函数
start,end=0,0 # 声明变量
start=time.time() # 记录开始时间
t=(t-3)/1000000 # 将输入t的单位转换为秒,-3是时间补偿
while end-start<t: # 循环至时间差值大于或等于设定值时
end=time.time() # 记录结束时间
a=time.time() # 记录延时函数开始执行时的时间
delayMicrosecond(10) #延时 35 微秒
b=time.time() # 记录延时函数结束时的时间
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")总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
