Home > front end >  should i use for loop or while loop to make a break timer in python?
should i use for loop or while loop to make a break timer in python?

Time:05-16

I have this code to stop a function at a specific time. I would loop thru the function and then break the function, if it takes too long, is there a better way to do it?

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

CodePudding user response:

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.
In general, what you need is:

  • set the start time
  • do whatever the function is supposed to be doing;
  • 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()

CodePudding user response:

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.

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()
  • Related