简体   繁体   English

我应该使用 for 循环还是 while 循环在 python 中制作一个中断计时器?

[英]should i use for loop or while loop to make a break timer in python?

I have this code to stop a function at a specific time.我有这段代码可以在特定时间停止 function。 I would loop through the function and then break the function, if it takes too long, is there a better way to do it?我会循环遍历 function 然后打破 function,如果时间太长,有没有更好的方法呢?

import time

def function_one()    
    rec = (time.time())
    print("im starting")
    ans = str(time.time() - rec)
    ans = (round(float(ans), 15))
    print("this is where im doing something code")
    while ans < 10:
          return function_one()
          break

You can make it simpler like this:您可以像这样使其更简单:

import time

def function_one():
    start_time = time.time()
    while True:
        print('Function doing something ...')
        if time.time() - start_time > 10:
            break


function_one()

Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.在这里,我使用 while 循环来保持 function 运行,但这取决于您的 function 的详细信息。
In general, what you need is:一般来说,你需要的是:

  • set the start time设置开始时间
  • do whatever the function is supposed to be doing;做 function 应该做的任何事情;
  • check if it's been running for too long and, in case it has, you can simply return.检查它是否运行时间过长,如果运行时间过长,您只需返回即可。

So, something like:所以,像这样:

import time

def function_one():
    start_time = time.time()
    # do your job
    if time.time() - start_time > 10:
        return something


function_one()

If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.如果你想在经过一定时间后停止 function,我会使用 while 循环并执行类似的操作。

import time
def function_one():
    start = (time.time()) #start time
    limit = 1 #time limit
    print("im starting")
    while (time.time() - start) < limit:
        #input code to do here
        pass
    print(f"finished after {time.time() - start} seconds")
function_one()

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

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