How can I accurately pause for a set length of time in python.
I've tried:
import time
time.sleep(amount)
(amount = a length in time less than 1 second)
however this isn't very accurate, is there any thing better?
(windows 10 , 64 bit)
How can I accurately pause for a set length of time in python.
I've tried:
import time
time.sleep(amount)
(amount = a length in time less than 1 second)
however this isn't very accurate, is there any thing better?
(windows 10 , 64 bit)
sleep will never be more accurate than the operating system's tick rate, for windows it's somewhere in the 10ms-16ms range , and in linux it can be as low as 1ms depending on the OS but typically it will be higher like windows
if you want a higher precision sleep and if you're on linux you can consider using nanosleep()
which is a high precision sleep function that unfortunately isn't exposed by python in any built in library - so you will need to create a small .so file which exposes it to python (either by importing it as is with ctypes or by making a C python module with cpython) this function according to the docs will be as precise as the timer itself can be
there are also high precision solutions for windows - but i never used any of them so i'm not qualified to recommend what to use on windows (but again you will need a .dll that exposes such methods to python)
with all that said if you dont care about power usage you can just do a busy sleep:
import time
def busy_sleep(seconds_to_sleep):
start = time.time()
while (time.time() < start + seconds_to_sleep):
pass
then you can call it like this busy_sleep(0.005)
and it will "sleep" almost exactly 0.005 seconds "sleep" is in air quotes since you aren't really sleeping you're keeping the cpu busy all this time at 100% but if what's important for you is to delay execution in a precise manner it could still work for you
Have you tried this? If I used time.sleep(1) it would wait one second. So,
time.sleep(0.33333333333)
# a third of a second pause.#
time.sleep(0.5)
# a half of a second pause.#
and so on. I'm sorry if this didn't awnser your question in the way you wanted!