首页 > 解决方案 > 如果需要超过 5 秒,则传递一个函数

问题描述

但是,我在 for 循环中调用了一个函数,我想检查该函数的执行时间是否超过 5 秒,我想通过该迭代并继续进行下一次迭代。

我考虑过使用时间库,并启动一个时钟,但结束计时器只会在函数执行后执行,因此我将无法在 5 秒内通过该特定迭代

标签: pythonpython-3.xtime

解决方案


我在下面附上一个例子。希望这可以帮助你:

from threading import Timer 
class LoopStopper: 
 
    def __init__(self, seconds): 
        self._loop_stop = False 
        self._seconds = seconds 
  
    def _stop_loop(self): 
        self._loop_stop = True 
 
    def run( self, generator_expression, task): 
        """ Execute a task a number of times based on the generator_expression""" 
        t = Timer(self._seconds, self._stop_loop) 
        t.start() 
        for i in generator_expression: 
            task(i) 
            if self._loop_stop: 
                break 
        t.cancel() # Cancel the timer if the loop ends ok. 
 
ls = LoopStopper( 5) # 5 second timeout 
ls.run( range(1000000), print) # print numbers from 0 to 999999

推荐阅读