简体   繁体   English

如何在python中创建计时器?

[英]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() . 我想要一个计时器,但是我希望它只影响一个函数,所以它不能只是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. 如果我使用sleep() ,那么我在一秒钟之内无法执行第一个函数,这对我来说是个问题。 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: 您可以像这样使用datetime库:

from datetime import datetime

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

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

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