比如这段:
1 2 3 4 5 6 7 8 9 |
import sched, time import datetime def whileOneSecond(): while True: print(datetime.datetime.now()) time.sleep(1) whileOneSecond() |
输出结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
2019-05-15 13:07:10.188710 2019-05-15 13:07:11.188965 2019-05-15 13:07:12.189855 2019-05-15 13:07:13.190381 2019-05-15 13:07:14.190849 2019-05-15 13:07:15.191828 2019-05-15 13:07:16.192440 2019-05-15 13:07:17.193014 2019-05-15 13:07:18.193326 2019-05-15 13:07:19.193606 2019-05-15 13:07:20.194679 2019-05-15 13:07:21.195403 2019-05-15 13:07:22.195706 2019-05-15 13:07:23.195851 2019-05-15 13:07:24.196235 2019-05-15 13:07:25.196626 2019-05-15 13:07:26.197574 2019-05-15 13:07:27.197850 2019-05-15 13:07:28.198161 2019-05-15 13:07:29.198770 2019-05-15 13:07:30.199328 2019-05-15 13:07:31.199998 |
这个一秒间隔算是准的 ,但这是因为程序中什么也没做
加入循环中有耗时大约为30 millisecond的代码 , 这里直接用 time.sleep(0.03)代替
1 2 3 4 5 6 7 8 9 10 |
import sched, time import datetime def whileOneSecond(): while True: print(datetime.datetime.now()) time.sleep(0.03) time.sleep(1) whileOneSecond() |
这样的输出结果就和每一秒执行一次的最初设计越来越远
所以, 要计算出 程序执行所占用的时间 , 并在 sleep 里减去这个时间
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import sched, time import datetime import random def whileOneSecond(): startMillSecond = int(time.time() * 1000) while True: print(datetime.datetime.now()) f= random.random()/10 #print(f) time.sleep(f) millSeondDiff = int(time.time() * 1000) - startMillSecond #time.sleep(1) time.sleep((1000-millSeondDiff)/1000) startMillSecond = int(time.time() * 1000) whileOneSecond() |