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(seconds/1000000.0)

time.sleep() takes seconds as a parameter.

http://docs.python.org/library/time.html#time.sleep


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

usleep(100) #sleep during 100μs

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 won't 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
            try:
                func(*args)
            except Exception as e:
                logger.error(e);
                if kwargs.get('exception'):
                    kwargs.get('exception')(e) # SEND exception to the specified function if there is one.
                else:
                    raise Exception(e)
    Thread(target=loop).start()
    return stopped.set

http://pastebin.com/0rZdY8gB


from time import sleep
sleep(0.1) #sleep during 100ms

Tags:

Python