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

TK.*_*TK. 467 python sleep timer

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

Wil*_*yce 730

from time import sleep
sleep(0.05)
Run Code Online (Sandbox Code Playgroud)

参考

  • @CsabaToth,只要您的Python实施符合您操作系统的规格,上述内容就是与操作系统无关的。 (3认同)
  • 但它“实际上”是如何运作的呢?例如,实际时间分辨率通常是 16.66 毫秒(1/60 秒)吗?在这种特殊情况下,睡眠时间恰好是时间分辨率的 3 倍。然而,四舍五入又如何呢?如果由于浮点运算,3 实际上是 2.9999999 并且向下舍入为 2(实际睡眠时间 = 0.0333333 s = 33.33 ms)怎么办? (2认同)
  • Python 代码库极不可能将 sleep(0.05) 舍入为 2 个系统时钟周期。它很可能会请求 3 个时钟周期,因为这是正确的答案。但系统可能会在 3、4、5 或 100 个时钟周期后返回。如果它正忙于执行其他操作(例如将数据刷新到磁盘),则无法保证它会在 3 个时钟周期后返回。如果时间紧迫,绝对不要使用此功能。如果您想要超准确的睡眠间隔,则必须在驱动程序级别编写代码来利用中断。 (2认同)

ya2*_*a23 69

请注意,如果您依赖睡眠时间恰好为 50毫秒,那么您将无法获得.它只是关于它.

  • 它可能比某些平台上的时间长10或15ms,因此请注意. (28认同)
  • 可能有趣的是,根据文档,自 Python 3.5 以来,“函数 [`time.sleep(secs)`] 睡眠*至少*“秒””。 (7认同)
  • 它是给定系统上的一致延迟吗? (4认同)
  • @ user391339从经验来看,这是不一致的。线程/进程优先级,平均CPU负载,可用内存以及大量其他因素使所有调用都不精确。系统越忙,不精确度越高。 (4认同)

Dan*_*son 60

import time
time.sleep(50 / 1000)
Run Code Online (Sandbox Code Playgroud)

  • 来自__future__进口部门的产品,以消除该陷阱。 (6认同)

小智 5

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

  1. sleep

    Sleep(参考)要求程序等待,然后执行其余的代码。

    有两种使用睡眠的方法:

    import time # Import whole time module
    print("0.00 seconds")
    time.sleep(0.05) # 50 milliseconds... make sure you put time. if you import time!
    print("0.05 seconds")
    
    Run Code Online (Sandbox Code Playgroud)

    第二种方式不导入整个模块,而只是休眠。

    from time import sleep # Just the sleep function from module time
    print("0.00 sec")
    sleep(0.05) # Don't put time. this time, as it will be confused. You did
                # not import the whole module
    print("0.05 sec")
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用自Unix 时间以来的时间

    如果您需要运行循环,这种方式很有用。但是这个稍微复杂一些。

    time_not_passed = True
    from time import time # You can import the whole module like last time. Just don't forget the time. before to signal it.
    
    init_time = time() # Or time.time() if whole module imported
    print("0.00 secs")
    while True: # Init loop
        if init_time + 0.05 <= time() and time_not_passed: # Time not passed variable is important as we want this to run once. !!! time.time() if whole module imported :O
            print("0.05 secs")
            time_not_passed = False
    
    Run Code Online (Sandbox Code Playgroud)

  • 不建议使用“time.time()”来测量经过的时间。最好使用 time.monotonic() ,它可以保证以统一的速率增加。在实际情况下,由于闰秒等原因,“time()”可能会因跳跃而改变。time.monotonic() 与 Linux 纪元时间没有绝对的相关性,但通常在系统启动时从 0 开始。 (4认同)