如何查看python代码部分是否在给定时间内完成

时间:2013-09-20 14:19:12

标签: python performance time

我想知道代码(Say a function call)是否在给定时间内完成。

例如,如果我调用的函数的参数是数组的元素

    #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循环的下一次迭代?

2 个答案:

答案 0 :(得分: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]))

答案 1 :(得分:0)

要干净利落地完成这项工作,您需要foo1()的合作。如果不这样做,那么您可以做的最好的事情是在另一个进程的上下文中运行foo1(),并在超时后终止该进程。