0

我想知道代码(比如函数调用)是否在给定时间内完成。

例如,如果我正在调用一个函数,其参数是数组的元素

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

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

如果 foo1 需要超过 x 秒才能返回值,是否有某种方法可以停止 foo1 执行并继续执行 for 循环的下一次迭代?

4

2 回答 2

2

对于这样的东西,我通常使用以下构造:

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()

然后电话会:

timeout = 5.2 #Time in sec
for i in range(len(arr1)):
    res1 = run_with_timeout(timeout, foo1,arr1[i]))
于 2013-09-20T14:53:09.677 回答
0

要干净、正确地执行此操作,您需要来自foo1(). 如果你不这样做,你能做的最好的就是foo1()在另一个进程的上下文中运行,并在超时后终止该进程。

于 2013-09-20T14:32:21.147 回答