【问题标题】:How do I make a timer in python?如何在python中制作计时器?
【发布时间】:2019-01-14 11:27:08
【问题描述】:

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

例如:

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

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

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

【问题讨论】:

标签: python timer sleep


【解决方案1】:

对于您的计时器功能,您可能需要执行以下操作:

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

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

编辑:要在这段时间内运行函数,您可以复制并缩短等待时间。示例:

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

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

【讨论】:

  • 他说不要使用 sleep()
【解决方案2】:

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

from datetime import datetime

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

【讨论】:

    猜你喜欢
    • 2013-03-26
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多