繁体   English   中英

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

[英]How to run a search that returns after a certain amount of time?

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM