usleep in Python

usleep in Python

Since usleep generally means you want to delay execution for x microseconds, you must divide the seconds value by 1000000.

import time

time.sleep() takes seconds as a parameter.

import time
usleep = lambda x: time.sleep(x/1000000.0)

usleep(100) #sleep during 100μs

usleep in Python

Be very very careful with time.sleep. I got burned by python3 using time.sleep because it is non-monotonic. If the wall clock changes backwards, the time.sleep call wont finish until the wall clock catches up with where it would have been if the sleep had gone forward as planned. I have not yet found a monotonic blocked sleep for python.

Instead, I recommend Event.wait, like this:

def call_repeatedly(interval, func, *args, **kwargs):
    stopped = Event()
    def loop():
        while not stopped.wait(interval):  # the first call is in `interval` secs
            except Exception as e:
                if kwargs.get(exception):
                    kwargs.get(exception)(e) # SEND exception to the specified function if there is one.
                    raise Exception(e)
    return stopped.set

Leave a Reply

Your email address will not be published. Required fields are marked *