pythontimesleepclockpulse

Create clock pulse with python


I want to work with exactly 20ms sleep time. When i was using time.sleep(0.02), i am facing many problems. It is not working what i want. If I had to give an example;

import time
i = 0
end = time.time() + 10
while time.time() < end:
    i += 1
    time.sleep(0.02)
    print(i)

We wait to see "500" in console. But it is like "320". It is a huge difference. Because sleep time is not working true and small deviations occur every sleep time. It is increasing cumulatively and we are seeing wrong result.

And then, i want to create my new project for clock pulse. Is it that possible with time.time()?

import time
first_time = time.time() * 100 #convert seconds to 10 * miliseconds
first_time = int(first_time) #convert integer

first_if = first_time
second_if = first_time + 2 #for sleep 20ms
third_if = first_time + 4 #for sleep 40ms
fourth_if = first_time + 6 #for sleep 60ms
fifth_if = first_time + 8 #for sleep 80ms

end = time.time() + 8
i = 0
while time.time() < end:
    now = time.time() * 100 #convert seconds to 10 * miliseconds
    now = int(now) #convert integer

    if i == 0 and (now == first_if or now > first_if):
        print('1_' + str(now))
        i = 1
    if i == 1 and (now == second_if or now > second_if):
        print('2_' + str(now))
        i = 2
    if  i == 2 and (now == third_if or now > third_if):
        print('3_' + str(now))
        i = 3
    if i == 3 and (now == fourth_if or now > fourth_if):
        print('4_' + str(now))
        i = 4
    if i == 4 and (now == fifth_if or now > fifth_if):
        print('5_' + str(now))
        break

Out >> 1_163255259009
       2_163255259011
       3_163255259013
       4_163255259015
       5_163255259017

Is this project true logic? And If it is true logic, how can finish this projects with true loops? Because i want these sleeps to happen all the time. Thank you in advice.


Solution

  • Let's say you want to count in increments of 20ms. You need to sleep for the portion of the loop that's not the comparison, increment, and print. Those operations take time, probably about 10ms based on your findings.

    If you want to do it in a loop, you can't hard code all the possible end times. You need to do something more general, like taking a remainder.

    Start with the time before the loop:

    t0 = time.time()
    while time.time() < end:
        i += 1
    

    Now you need to figure out how long to sleep so that the time between t0 and the end of the sleep is a multiple of 20ms.

    (time.time() - t0) % 0.02 tells you how far past a 20ms increment you are because python conveniently supports floating point modulo. The amount of time to wait is then

        time.sleep(0.02 - (time.time() - t0) % 0.02)
        print(i)
    

    Using sign rules of %, you can reduce the calculation to

        time.sleep(-(time.time() - t0) % 0.02)