如何运行一段时间后返回的搜索?
问题描述:
我有一个运行迭代深化搜索,想的一定时间过去之后,从最深的搜索返回值的函数。代码框架看起来像如何运行一段时间后返回的搜索?
import time
answers = []
START = time.clock()
current_depth = 1
while time.clock() - START < DESIRED_RUN_TIME:
answers.append(IDS(depth=current_depth))
current_depth += 1
return answers[-1]
的问题与此代码是它不会返回,直到时限过后。解决这个问题的最好方法是什么?如果我只需在IDS函数中添加时间检查,我如何确保返回找到的最后一个值?任何帮助将不胜感激。
答
您的代码应该工作,除非IDS
阻止,并采取了很长的时间。然后你必须等到IDS完成,时间限制可能不会那么精确。
我不知道你所说的
的意思到底是什么想的一定时间过去之后,从最深的搜索返回的值。
和
这段代码的问题是,它不会返回,直到时限过后。
如果您有时间限制并且有更新时间,那么您可以将此代码用作生成器。
import time
answers = []
START = time.clock()
current_depth = 1
def get_ids(update_time, limit_time):
last_update = time.clock()
while time.clock() - START < DESIRED_RUN_TIME:
answers.append(IDS(depth=current_depth))
current_depth += 1
if time.clock() - last_update < update_time:
last_update = time.clock()
yield answers[-1]
yield answers[-1]
for i in get_ids(1, 10): # get an ids every second and stop after 10 seconds
print(i)
对于搜索问题,我保留了一个全球“最好”的答案,搜索分支更新了它,因为他们找到了更好的答案。如果你有一个线程进行搜索,你不会遇到线程安全问题,否则你需要锁定/关键部分/任何更新最好。 –