【问题标题】:Basic timer in Python 3.7 [closed]Python 3.7 中的基本计时器 [关闭]
【发布时间】:2018-09-07 18:35:06
【问题描述】:

由于我对 Stack Overflow、Python 和一般写作技巧的了解不足,我没有具体说明我正在使用 pygame 模块这一事实。非常抱歉我缺乏理解,我会努力改进。

大约 2-3 天前开始学习 Python。最近遇到了我实现计时器的问题。我正在使用time.sleep(10),但后来发现这实际上将代码暂停了 10 秒,而我需要它来计算 10 秒。有没有办法我可以做到这一点?非常感谢。

编辑:我现在明白“计时器”这个词可能不是最合适的。我实际上想要做的是创造一个 10 秒的冷却时间。

【问题讨论】:

  • 您的代码改为暂停 1 秒 10 次有意义吗?或者定期检查时间是否已过 10 秒?解决此类问题的策略有很多,选择正确的策略需要更多详细信息来说明您正在尝试做什么。
  • 计数 10 秒而不是睡觉是什么意思?你需要警报吗?你需要信号吗?
  • 猜测,您可能正在寻找pygame.time.set_timer
  • "Timer" 是一个非常好的术语(实际上,您正在寻找的东西甚至可以在 PyGame 中称为“计时器”,或线程,或其他)。只是它是一个模棱两可的词,所以您需要向我们提供更多信息,以便我们了解上下文。
  • 你真的应该提到这是为 PyGame 准备的。在 GUI 程序中执行时间延迟与在 CLI 程序中执行此操作完全不同,因此您问题的所有现有答案都无关紧要。

标签: python python-3.x pygame python-3.7


【解决方案1】:

我认为您遇到的问题是您的代码是按顺序运行的。如果您希望在运行其余代码的同时运行一些代码(有点像在后台运行),您可以使用Threading

import threading
import time

def in_thread():
    print("Thread start")
    time.sleep(10)
    print("Thread end")

print("Start")
thread = threading.Thread(target=in_thread)
thread.start()
print("This continues")

但是,如果您将此作为游戏中的冷却系统,我建议您存储 time.time(),它以秒为单位给出当前时间,即第一次采取行动的时间。当他们再次尝试执行该操作时,您可以将当前时间与您存储的时间进行比较,看看他们是否已经过了冷却时间 (time.time() - startTime > 10:)。

【讨论】:

  • 您的回答真棒!我希望你不会介意一点点指针;您应该解释这个答案如何解决 OP-s 问题。它在做什么?为什么它有效?我什至不确定这是否能回答问题,如果您误解了 OP 的问题,而没有解释您的解释,那么您最终可能会投反对票。再说一遍:很高兴有你加入,你正在努力提供帮助,而这正是我想要做的!
  • @AndreasStorvikStrauman 感谢您的建议。我已经更新了我的答案。
  • 完美!很好的答案!
【解决方案2】:

编辑 2: 冷却时间:

以下代码

import time
import random
# Minimum time (in seconds) that it has to wait
for i in range(10):
    minimum_time=3
    tick=time.time()
    # How much time has passed since tick?
    passed_time=time.time()-tick
    # Sleep a random amount of time
    time.sleep(random.uniform(0,3))
    # Check if the passed time is less than the minimum time
    if passed_time<minimum_time:
        # If it is not passed enough time
        # then sleep the remaining time
        time.sleep(minimum_time-passed_time)

    print("{} seconds were used in this iteration of the loop, and it should be _at least_ 3".format(time.time()-tick))

编辑:这可能是你想要的:

import time
for i in range(1,11):
    print(i)
    time.sleep(1)

这个从 1 数到 10。你可以把它倒过来

import time
for i in reversed(range(1,11)):
    print(i)
    time.sleep(1)

下面的第一个答案

这是你可以在 python 中做一个基本计时器的一种方法:

import time
# Get the current unix time stamp (that is time in seconds from 1970-01-01)
first=time.time()
# Sleep (pause the script) for 10 seconds
# (remove the line below and insert your code there instead)
time.sleep(10)
# Get the _now_ current time (also in seconds from 1970-01-01)
# and see how many seconds ago we did it last time
delta=time.time()-first
print(delta)

现在打印(大约)10,因为运行上述代码需要 10 秒。

你也可以看看iPythons %timeit

附录

你也可以把它做得更大,创建一个 Timer 类,像这样:

import time
class Timer():
    def __init__(self):
        self.times=[]
        self._tick=0
    def tick(self):
        """ Call this to start timer """
        # Store the current time in _tick
        self._tick=time.time()
    def tock(self):
        """ Call this to stop timer """
        # Add the delta in the times-list
        self.times.append(time.time()-self._tick)
    def __str__(self):
        # This method is just so that the timer can be printed nicely
        # as further below
        return str(self.times)

现在您可以运行t=Timer(),然后运行t.tick()t.tock() 来分别启动和停止计时器(多次(!)),然后运行print(t) 来查看所有记录的时间。例如

t=Timer()
for i in range(4):
    t.tick()
    # Sleep (pause the script) for 10 seconds
    # (remove the line below and insert your code there instead)
    time.sleep(1)
    # Get the _now_ current time (also in seconds from 1970-01-01)
    # and see how many seconds ago we did it last time
    t.tock()
print(t)

【讨论】:

  • 当我运行这段 sn-p 代码时,它会暂停我脚本中的所有其他内容。我想要一些重要的东西,而不会暂停我的其余代码。
  • 它会暂停 10 秒。只需从我的代码中删除time.sleep 部分,然后插入您想要计时的代码
  • 也许计时器是错误的术语。我想要一些模拟冷却的东西。
  • @archieab 很抱歉,但我不明白你的意思是冷却更好吗?
  • @archieab 现在查看修改后的答案
【解决方案3】:

你可以使用threading.Timer设置定时器:

threading.Timer

经过指定时间间隔后执行函数的线程。

>>> import threading
>>> def hello():
...     print("Hello")
...
>>> t =threading.Timer(5, hello)
>>> t.start()
 Hello

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2013-12-30
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多