python中的时间机制包含2种:
time.time 精度为15.6ms
time.clock精度为1ms
方法1:
import time
#延迟tms定时器
def delayMsecond(t):
start,end = 0,0
start = time.time() * pow(10,7) #精确至ns级别
while(end - start < t* pow(10,3)):
end = time.time() * pow(10,7)
for index in range(1,10):
startTime = time.time()
delayMsecond(1)
endTime = time.time()
dif = (endTime - startTime) * 1000
print(dif)
测试结果:误差接近1ms
方法二:
import time
#延迟ms定时器
def delayMsecond(t):
start,end = 0,0
start = time.clock() * pow(10,7)
while(end - start < t* pow(10,3)):
end = time.clock() * pow(10,7)
for index in range(0,50):
start = time.clock()
delayMsecond(1)
end = time.clock()
dif = (end - start)*pow(10,3)
print(dif)
测试结果: 0.1ms---perfect