Let's say I have a Python script which is designed to wait for a specific amount of time in milliseconds and then press a key on the keyboard. Should I use threading.Timer()
or should I just do it with time.sleep()
? Which one is more accurate in terms of pressing the key on time and which one is more efficient?
Also, please let me know if there are better and more accurate ways to do this.
threading.Timer()
runs in a separate thread, which means it won't block your main program. However, it can be less precise due to thread scheduling overhead and context switching.
time.sleep()
is more accurate for short durations (milliseconds range) since it doesn't involve thread creation overhead. However, it blocks the entire program while waiting.
A third option worth considering is using Python's asyncio
, which can provide good timing accuracy without blocking.