如何限制循环中函数调用的执行时间

问题描述 投票:0回答:2

我有一个循环,它调用一个有时会挂起的函数(下面的示例)。我找到了一些关于如何限制函数调用的执行时间的示例。然而,它们在循环情况下会失败,因为当中断信号发生时,我们可能正在下一个循环的中间。有没有办法限制下面代码的执行时间?

def perhaps_long_exec():
  if random.random() < 0.5:
    while True:
      pass

for i in range(100)
  # limit execution time of below function call
  perhaps_long_exec()
python multithreading timeout python-multithreading
2个回答
1
投票

使用多重处理似乎是一个不错的解决方案。 为每个循环创建一个新进程,如果卡住就杀死它。

import random
import time
from multiprocessing import Process


def perhaps_long_exec():
    x = random.random()
    print(x)
    if x < 0.5:
        print('Stuck!')
        while True:
            pass
    else:
        print('Fine')
        exit()


if __name__ == '__main__':
    for i in range(100):
        p = Process(target=perhaps_long_exec)  # make process
        p.start()  # start function
        time.sleep(3)  # wait 3 secs
        if p.is_alive(): # check if process is still going
            p.terminate()  # kill it
            print('killed')

输出:

> 0.26936380878403265
> Stuck!
> Killed
> 0.5185183414607246
> Fine
> 0.4361287927947891
> Stuck!
> Killed

0
投票

您必须检查函数本身内部已经过去了多少时间,我认为除非使用线程,否则您不能从外部中断函数。

import time

SECONDS = 1
MINUTES = 60 * SECONDS
HOURS = 60 * MINUTES
TIME_LIMIT_IN_SECONDS = 2*HOURS

def perhaps_long_exec():
  if random.random() < 0.5:
    start_time = time.time()
    while True:
      current_time = time.time()
      if current_time-start_time > TIME_LIMIT_IN_SECONDS:
        break
      pass

for i in range(100)
  # limit execution time of below function call
  perhaps_long_exec()
© www.soinside.com 2019 - 2024. All rights reserved.