如何在 python 中制作计时器?

How do I make a timer in python?

我想要一个计时器,但我希望它只影响一个功能,所以它不能只是 sleep().

例如:

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

假设单击按钮时调用第一个函数,第二个函数应每秒打印一些内容,两者应独立运行。

如果我使用sleep(),我无法在那一秒内执行第一个功能,这对我来说是个问题。我该如何解决这个问题?

对于你的定时器功能,你可能想做这样的事情:

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

这将向后打印范围(如倒计时),每秒一个数字。

EDIT: 要运行 那个时间的一个函数,你可以复制和缩短等待时间。示例:

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

您可以稍微调整一下时间,以便获得合适的输出。

您可以像这样使用日期时间库:

from datetime import datetime

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