I'm making a digital clock in python for minecraft pi edition. I'm using a single while loop that contains a lot of code - it takes a short time to execute one run of it, but it's a few milliseconds more than I want, and this is wreaking havoc on my clock. Is there a way to make a while loop completely accurate? I'm using two counts of time.sleep(1)
, but it's taking longer than two seconds to execute.
Example:
while True:
start = time.time()
for _ in range(5):
1000**3
time.sleep(1)
print (time.time() - start)
Which takes more than 1 second per loop.
1.00102806091
1.00028204918
1.00103116035
1.00051879883
1.0010240078
1.00102782249
This error accumulates over time. How can I prevent it from drifting?