如何使while循环花费一定的时间 [英] How to make while loops take a set amount of time

查看:80
本文介绍了如何使while循环花费一定的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 为我的世界 pi 版制作一个数字时钟.我正在使用一个包含大量代码的 while 循环 - 执行一次它需要很短的时间,但它比我想要的多几毫秒,这对我的时钟造成了严重破坏.有没有办法让while循环完全准确?我使用了两次 time.sleep(1),但执行时间超过两秒.

示例:

虽然为真:开始 = time.time()对于 _ 范围(5):1000**3时间.睡眠(1)打印(时间.时间() - 开始)

每个循环需要超过 1 秒.

1.001028060911.000282049181.001031160351.000518798831.00102400781.00102782249

此错误会随着时间的推移而累积.我怎样才能防止它漂移?

解决方案

您可以编写时间同步代码(此示例取自我拥有的服务器监视器):

# 同步时间,使其每两分钟运行一次,以 20 分钟为周期 (:00, :20, :40)time.sleep(1200 - (time.time() % 1200))为真:# 做东西time.sleep(120 - (time.time() % 120))

如果你想每两秒运行一次:

time.sleep(2 - (time.time() % 2))

让它休眠直到下一秒,然后运行.除非Do stuff 的时间超过一个周期,否则这将起作用.然后它会跳过一个节拍.

对于时钟,示例输出:

<预><代码>>>>对于 _ 范围(5):... time.sleep(1 - (time.time() % 1))... 打印 time.time()1478641441.01478641442.01478641443.01478641444.01478641445.0

<小时>

这是有效的,因为 time.time() % 1 只给出当前时间的几分之一秒:例如 0.37.当我说 time.sleep(1 - 0.37) 时,它会休眠 0.63 秒,这是到下一轮的剩余时间.

如果下次运行我的代码需要 0.55 秒,它会自动休眠剩余的 0.45.

I'm making a digital clock in python for minecraft pi edition. I'm using a single while loop that contains a lot of code - it takes a short time to execute one run of it, but it's a few milliseconds more than I want, and this is wreaking havoc on my clock. Is there a way to make a while loop completely accurate? I'm using two counts of time.sleep(1), but it's taking longer than two seconds to execute.

Example:

while True:
    start = time.time()
    for _ in range(5):
        1000**3
    time.sleep(1)
    print (time.time() - start)

Which takes more than 1 second per loop.

1.00102806091
1.00028204918
1.00103116035
1.00051879883
1.0010240078
1.00102782249

This error accumulates over time. How can I prevent it from drifting?

解决方案

You can write time synchronization code (this sample taken from a server monitor I have):

# sync time so that it runs every two minutes, in 20 minute cycles (:00, :20, :40)
    time.sleep(1200 - (time.time() % 1200))
    while True:
        # Do stuff
        time.sleep(120 - (time.time() % 120))

If you want to run something every two seconds:

time.sleep(2 - (time.time() % 2)) 

will make it sleep until the next even second, then run. This will work unless the time to Do stuff exceeds a cycle. It will then skip a beat.

For a clock, example output:

>>> for _ in range(5): 
...     time.sleep(1 - (time.time() % 1)) 
...     print time.time()
1478641441.0
1478641442.0
1478641443.0
1478641444.0
1478641445.0


This works because time.time() % 1 gives just the fraction of a second from the current time: 0.37 for example. When I say time.sleep(1 - 0.37) it sleeps for 0.63 seconds, which is the time remaining until the next round second.

If next time it takes 0.55 seconds to run my code, it will sleep the remaining 0.45 automatically.

这篇关于如何使while循环花费一定的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆