Python 3.7 中的基本计时器

新手上路,请多包涵

由于我对 Stack Overflow、Python 和一般写作技巧知之甚少,我没有说明我正在使用 pygame 模块这一事实。我对我缺乏理解感到非常抱歉,并且会致力于改进。

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

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

原文由 user10332166 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 547
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 秒。

您还可以查看 iPython s %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)

Now you can just run t=Timer() followed by t.tick() and t.tock() to start and stop the timer respectively (multiple times(!)), and then 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)

原文由 Andreas Storvik Strauman 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 Nelson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题