Python 如果函数尚未完成,则使用timeout返回
我有以下情况:Python 如果函数尚未完成,则使用timeout返回,python,timeout,Python,Timeout,我有以下情况: 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 l
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
毫秒。我不知道如何在主线程中从这两个方面得到结果,并决定哪一个先到。如果您对这种方法或其他方法有任何建议,我们将不胜感激。您可以使用时间。性能计数器
您的代码将看到:
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
导入时间
ProcessTime=time.perf_counter#如果python版本为0:
睡眠(1)
其他:
返回#错误或错误
对于每个任务的for循环,您可以更改,检查timeout如果您要应用多处理,则只需应用
p.join(timeout=5)
其中p在进程中
下面是一个简单的例子
导入时间
从itertools导入计数
从多处理导入进程
def inc_forever():
打印('Starting function inc_forever()…'))
尽管如此:
时间。睡眠(1)
打印(下一个(计数器))
def return_zero():
print('Starting function return_zero()…')
返回0
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#计数器是一个无限迭代器
计数器=计数(0)
p1=过程(目标=永远持续,名称=“过程永远持续”)
p2=进程(目标=返回0,name='Process\u return\u zero')
p1.开始()
p2.start()
p1.加入(超时=5)
p2.加入(超时=5)
p1.终止()
p2.终止()
如果p1.exitcode为无:
打印(f'Oops,{p1}超时!')
如果p2.exitcode==0:
打印(f'{p2}很幸运,在5秒钟内完成!)
我想这可能会对您有所帮助这需要毫秒超时吗?是的,delta是一个浮点,而sleep()接受0.01秒我试图将其称为longfunc(1,0.05)。。。ProcessTime=time.perf_计数器def longfunc(count,timeout):res=[]范围内i的start=ProcessTime()(count):delta=start+timeout-ProcessTime(),如果delta>0:time.sleep(1)res=[1]*10返回res0.05s这是一个非常短的时间,您需要其他条件