如何让我的程序休眠50毫秒?

764

我该如何让我的Python程序休眠50毫秒?

6个回答

1141

2
但它实际上是如何工作的?例如,实际时间分辨率是否经常为16.66毫秒(1/60秒)?在这种特殊情况下,睡眠时间恰好是时间分辨率的三倍。然而,四舍五入呢?如果3实际上是由于浮点运算而变成2.9999999,并且被舍入为2(实际睡眠时间= 0.0333333秒= 33.33毫秒),那该怎么办? - Peter Mortensen
1
极不可能发生的情况是,Python代码库将睡眠(0.05)舍入为2个系统时钟滴答声。它很可能会请求3个时钟滴答声,因为那是正确的答案。但是,如果系统正在执行其他操作(例如将数据刷新到磁盘),则它可能在3个或4个或5个或100个时钟滴答后返回。如果时间关键,则绝对不要使用此功能。如果您想要超级准确的睡眠间隔,您必须编写驱动程序级别的代码来利用中断。 - Mark Lakata

119
请注意,如果您依赖于精确的50毫秒的休眠,那么您将无法得到精确的50毫秒。它只会接近这个值。

48
在某些平台上可能会比那个时间长10或15毫秒,所以请注意。 - Kylotan
5
在给定系统中,这是否是一个连续的延迟? - user391339
12
根据经验,它不是一致的。线程/进程优先级、CPU负载平均值、可用内存以及其他各种因素都会导致所有调用不精确。系统越忙碌,误差就越大。 - David
11
有趣的是,根据Python 3.5文档,函数time.sleep(secs)至少会休眠secs秒。 - Elias Strehle

96

17

有一个名为“time”的模块可以帮助你。我知道两种方法:

  1. sleep

    sleep参考)让程序等待一段时间,然后再执行其余的代码。

    有两种使用 sleep 的方法:

    import time # 导入整个 time 模块
    print("0.00 秒")
    time.sleep(0.05) # 50 毫秒……确保你导入了 time!
    print("0.05 秒")
    

    第二种方法不会导入整个模块,只是让它睡眠。

    from time import sleep # 从 time 模块中仅导入 sleep 函数
    print("0.00 秒")
    sleep(0.05) # 这次不要加 time.,否则会混淆。你没有导入整个模块
    print("0.05 秒")
    
  2. 使用 time.monotonic() 计算自开机以来的时间。

    如果需要循环运行,这种方式非常有用。但这种方式稍微复杂一些。time.monotonictime.time 更好,因为它不考虑闰秒,而是计算自开机以来的时间。(来源:Mark Lakata

    time_not_passed = True
    from time import monotonic as time # 导入 time.monotonic,但为了简单起见将其命名为“time”
    
    init_time = time() # 如果导入整个模块,则使用 time.monotonic()
    print("0.00 秒")
    while True: # 初始化循环
        if init_time + 0.05 <= time() and time_not_passed: # 时间未过变量很重要,因为我们只想运行一次。!!! 如果导入整个模块,则使用 time.monotonic() :O
            print("0.05 秒")
            time_not_passed = False
    

4
不建议使用 time.time() 来测量经过的时间。最好使用 time.monotonic(),它保证以均匀的速率增加。实际上有些情况下 time() 可能会因为闰秒等原因而跳变。time.monotonic() 与 Linux 纪元时间没有绝对的关联,但通常在系统启动时从 0 开始计数。 - Mark Lakata
我可以把 time.time() 改成 time.monotonic()。 - Lucas Urban

4
你可以使用Timer()函数来实现。
代码:
from threading import Timer

def hello():
  print("Hello")

t = Timer(0.05, hello)
t.start()  # After 0.05 seconds, "Hello" will be printed

对于亚秒级别的睡眠,它实际上是如何工作的?通常计时器的时间分辨率为16.66毫秒。 - Peter Mortensen

1

你也可以将pyautogui用作:

import pyautogui
pyautogui._autoPause(0.05, False)

如果第一个参数不是None,则会暂停第一个参数的秒数,例如:0.05秒。
如果第一个参数为None,并且第二个参数为True,则会休眠全局暂停设置,该设置使用以下命令进行设置:
pyautogui.PAUSE = int

如果你想知道原因,可以查看源代码:
def _autoPause(pause, _pause):
    """If `pause` is not `None`, then sleep for `pause` seconds.
    If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).

    This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
    is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
    is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
    is as long as `pause` seconds.
    """
    if pause is not None:
        time.sleep(pause)
    elif _pause:
        assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
        time.sleep(PAUSE)

2
不过,最好使用time.sleep,而不是这种方法,但如果你想让你的程序纯粹使用autopygui,那么这也是一种方式。 - okie
pyautogui 使用 time.sleep()。 - Anton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接