简体   繁体   中英

How do I make a timer in python?

I want a timer, but I want it to just affect one function, so it can't just be sleep() .

For example:

def printSomething():
    print("Something")
def functionWithTheTimer():
    for i in range(0, 5):
        #wait for 1 second
        print("Timer ran out")

Say the first function is called when a button is clicked, and the second function should print something out every second, both should act independently.

If I used sleep() , I couldn't execute the first function within that one second, and that's a problem for me. How do I fix this?

For your timer function, you may want to do something like this:

def functionWithTheTimer():
    for i in reversed(range(1, 6)):
        print(i)
        time.sleep(1)
    print("finished")

This will print the range backwards (like a countdown), one number every second.

EDIT : To run a function during that time, you can just duplicate and shorten the wait time. Example:

def functionWithTheTimer():
    for i in reversed(range(1, 6)):
        print(i)
        time.sleep(0.5)
        YourFunctionHere()
        time.sleep(0.5)
    print("finished")

You can play with the timings a little so you can get your appropriate output.

You can use the datetime library like this:

from datetime import datetime

def functionwithtimer():
   start_time = datetime.now()
   # code stuff you have here 
   print("This function took: ", datetime.now() - start_time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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