如何运行在一定时间后返回的搜索?

时间:2017-06-05 19:38:40

标签: python python-3.x

我有一个运行迭代加深搜索的函数,并希望在经过一定时间后从最深的搜索返回值。代码框架看起来像

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函数中添加时间检查,我该如何确保返回找到的最后一个值?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

除非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)
相关问题