Python 3.7 中的基本计时器

Basic timer in Python 3.7

由于我对 Stack Overflow、Python 和一般写作技巧知之甚少,所以我没有说明我正在使用 pygame 模块这一事实。对我的理解不够深表歉意,会努力改进的。

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

编辑:我现在明白 'timer' 这个词可能不是最合适的。我实际上想做的是创建 10 秒的冷却时间。

编辑 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 class,像这样:

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)

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

class threading.Timer

A thread that executes a function after a specified interval has passed.

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

我认为您 运行 遇到的问题是您的代码按顺序运行。如果您希望在其余代码运行的同时拥有一些代码 运行(有点像在后台运行),您可以使用 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:)。