Search code examples
pythonperformanceselecttimesleep

What's the most efficient way to sleep in Python?


What would be better ?

time.sleep(delayTime)

or

select.select([],[],[],delayTime)

Are they equivalent ? Is select more efficient?


Solution

  • The answer depends on what your trying to achieve:

    time.sleep(delayTime)
    • Action: Suspend execution of the current thread for the given number of seconds.
    • Any caught signal will terminate the sleep() following execution of that signal’s catching routine
    select.select([],[],[],delayTime)

    This is a straightforward interface to the Unix select() system call. The first three arguments are sequences of ‘waitable objects’:

    • rlist: wait until ready for reading
    • wlist: wait until ready for writing
    • xlist: wait for an “exceptional condition”

    So now, that we understand the two interfaces we can understand that the answer depends on the purpose:
    If all you want to do is to suspend the current thread - the first option is simpler. But if there are objects to wait on - use the second method. In temp of efficiency - I don't think there are differences if all you are looking for is the simplest use-case (just suspend the main thread).