Hi I have a question regarding to the
from timeit import default_timer as timer
my_points = [1,2,3,4,5,6,7,8,9,10,
start = timer()
for i in my_points:
print (i, flush = True)
time.sleep(0.001) #Problem is here
end = timer()
print ("Total time run per cycle: ", end - start)
time.sleep(2) #To read the time
The manual entry for time.sleep
Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.
Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).
makes it pretty clear that the actual sleep time will only approximate the requested time. I have separately read that the resolution on Windows is 1/60 s, though I don't know if that is still true.
You can do much better using the tkinter root.after function. When I run the following in IDLE
import tkinter as tk from time import perf_counter as timer root = tk.Tk() n = 1000 def tick(): global n if n: #print(n) root.after(1, tick) n -= 1 else: print(timer() - start) root.quit() root.after(1, tick) start = timer() root.mainloop()
the output is repeatably just under 1.05 seconds, very close to the target 1.00. If I uncomment the tick print statement, the time is 4.2 seconds. In IDLE, the print goes through a socket to a separate process, which is a bit slow. Running in Windows Command Prompt, the 1000 print time is 1.3 seconds. I expect that this is about what you would get outputting to a serial post as long as the recipient can keep up with the flow.
EDIT One could do something similar with the relatively new
asyncio module, and with a bit more effort, even use the newer
async for syntax. But I do not have the needed knowledge memorized.