如果函数尚未完成,则使用超时 return

Use timeout to return if function has not finished

我有以下场景:

res = []

def longfunc(arg):
    # function runs arg number of steps
    # each step can take 500 ms to 2 seconds to complete
    # longfunc keeps adding result of each step into the array res 

def getResult(arg,timeout):
    # should call longfunc()
    # if longfunc() has not provided result by timeout milliseconds then return None
    # if there is partial result in res by timeout milliseconds then return res
    # if longfunc() ends before timeout milliseconds then return complete result of longfunc i.e. res array

result = getResult(2, 500)

我正在考虑使用multiprocessing.Process()longfunc()放在一个单独的进程中,然后启动另一个线程休眠timeout毫秒。我无法弄清楚如何在主线程中从它们两个中获得结果并决定哪个先出现。对这种方法或其他方法的任何建议表示赞赏。

您可以使用 time.perf_counter,您的代码将看到:

import time 
ProcessTime = time.perf_counter  #this returns nearly 0 when first call it if python version <= 3.6
ProcessTime() 
def longfunc(arg, timeout):
    start = ProcessTime()
    while True
        # Do anything
        delta = start + timeout - ProcessTime()
        if delta > 0:
            sleep(1)
        else:
            return #Error or False 
    

您可以为 for 循环更改 While 并为每个任务检查超时

如果您正在应用多处理,那么您只需应用 p.join(timeout=5) where p in a process 这是一个简单的例子

import time
from itertools import count
from multiprocessing import Process
def inc_forever():
    print('Starting function inc_forever()...')
    while True:
        time.sleep(1)
        print(next(counter))
def return_zero():
    print('Starting function return_zero()...')
    return 0
if __name__ == '__main__':
    # counter is an infinite iterator
    counter = count(0)
    p1 = Process(target=inc_forever, name='Process_inc_forever')
    p2 = Process(target=return_zero, name='Process_return_zero')
    p1.start()
    p2.start()
    p1.join(timeout=5)
    p2.join(timeout=5)
    p1.terminate()
    p2.terminate()
if p1.exitcode is None:
       print(f'Oops, {p1} timeouts!')
if p2.exitcode == 0:
        print(f'{p2} is luck and finishes in 5 seconds!')

我觉得可能对你有帮助