tdk
tdk

Reputation: 342

How to see if section of python code completes within a given time

I wish to find out if code (Say a function call) completes within a given time.

For example if I am calling a function with parameters that are elements of an array

    #arr1 is some array
    #foo1 is an array that returns something

    for i in range(len(arr1)):
        res1 = foo1(arr1[i])  #calling the function

Is there some way by which I can stop foo1 executing and continue with the next iteration of the for loop if foo1 takes more than x seconds to return a value?

Upvotes: 0

Views: 113

Answers (2)

Robert Caspary
Robert Caspary

Reputation: 1634

For stuff like that I normally use the following construct:

from threading import Timer
import thread

def run_with_timeout( timeout, func, *args, **kwargs ):
    """ Function to execute a func for the maximal time of timeout.
    [IN]timeout        Max execution time for the func
    [IN]func           Reference of the function/method to be executed
    [IN]args & kwargs  Will be passed to the func call
    """
    try:
        # Raises a KeyboardInterrupt if timer triggers
        timeout_timer = Timer( timeout, thread.interrupt_main )
        timeout_timer.start()
        return func( *args, **kwargs )
    except KeyboardInterrupt:
        print "run_with_timeout timed out, when running '%s'" %  func.__name__
        #Normally I raise here my own exception
    finally:
        timeout_timer.cancel()

Then the call would like:

timeout = 5.2 #Time in sec
for i in range(len(arr1)):
    res1 = run_with_timeout(timeout, foo1,arr1[i]))

Upvotes: 2

NPE
NPE

Reputation: 500903

To do this cleanly and correctly, you need cooperation from foo1(). If you don't, the best you can do is to run foo1() in the context of another process, and to kill that process after a timeout.

Upvotes: 0

Related Questions