python - 如何停止运行 func 并在一分钟后返回 value ?

我想调用一个函数并在一分钟后停止运行,返回一个value。我有一个看起来类似于的代码:

def foo(txt):
   best_value=-1
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
    return best_value

我想在一分钟后停止运行并返回 best_value。谢谢你的帮助。

回答1

一个相对愚蠢但可能令人满意的解决方案是设置一个计时器并在每次循环迭代时检查它:

import time

def foo(txt):
   best_value=-1
   curr_time = time.time()
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
       if time.time() - curr_time > 60:
           break
    return best_value

这里最大的缺点是大量计算浪费在检查上,我们必须执行 https://man7.org/linux/man-pages/man2/time.2.html 来检索 time。我们可以通过检查每 1000 个单词(例如)来缓解这种情况,如下所示:

import time

def foo(txt):
   best_value=-1
   curr_time = time.time()
   for i, word in enumerate(txt):
       if value(word)>best_value:
           best_value=value(world)
       if i % 1000 == 0 and time.time() - curr_time > 60:
           break
    return best_value

这只会对 i % 1000 进行更便宜的检查,并且会在计算 time.time() - curr_time > 60 之前短路。

这可能已经足够好了,但如果你想要更多,这里有另一个可能的角度。

在两个独立的进程之间更新一些共享内存,其中一个进程进行计算并更新一些共享内存,另一个进程负责休眠 60 秒然后杀死另一个进程。

https://docs.python.org/3/library/multiprocessing.shared_memory.html 如果您选择走那条路,可能会非常有用。

回答2

如果您想将时序代码与业务逻辑解耦并将开销降至最低,一种简单的方法是在代码中使用全局变量来告诉它何时停止运行:

time_out = False

def foo(txt):
   best_value=-1
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
       if time_out:
           break
    return best_value

然后使用一个单独的函数绑定到使用 https://docs.python.org/3/library/threading.html#timer-objects 来停止它:

def send_stop():
    global time_out
    time_out = True

Timer(60.0, send_stop).start() 
best_value = foo(corpus)

相似文章

随机推荐

最新文章