【问题标题】:Is `asyncio.sleep(delay)` guarenteed to sleep for at least `delay` seconds?`asyncio.sleep(delay)` 是否保证睡眠至少 `delay` 秒?
【发布时间】:2021-01-14 08:48:21
【问题描述】:

asyncio.sleep() 的阻塞表亲 time.sleep() 不能保证它会在请求的时间内休眠。

实际的挂起时间可能少于请求的时间,因为任何捕获的信号都会在执行该信号的捕获例程后终止 sleep()。

asyncio.sleep() 的documentation 没有提到类似的限制。

asyncio.sleep() 能否对睡眠时间做出更有力的保证?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    我不会告诉asyncio是什么保证,但根据实现,asyncio.sleep()(基本上,call_later())会在指定的时间间隔内休眠,但在至少与实现中使用的系统时钟的分辨率相同的不准确性。

    让我们弄清楚。首先,asyncio 使用单调时钟,它们具有不同的分辨率on different platforms(Python 和 OS 分辨率)。例如,对于Windows,这与15ms 一样多。

    在保证方面,请注意对函数BaseEventLoop.time的注释:

        def time(self):
            """Return the time according to the event loop's clock.
            This is a float expressed in seconds since an epoch, but the
            epoch, precision, accuracy and drift are unspecified and may
            differ per event loop.
            """
            return time.monotonic()
    

    现在我们来看看负责启动定时定时器的asyncio事件循环源code:

            # Handle 'later' callbacks that are ready.
            end_time = self.time() + self._clock_resolution
            while self._scheduled:
                handle = self._scheduled[0]
                if handle._when >= end_time:
                    break
                handle = heapq.heappop(self._scheduled)
                handle._scheduled = False
                self._ready.append(handle)
    

    end_time = self.time() + self._clock_resolution 行显示回调可能比计划的更早触发,但在时钟分辨率范围内。 Yuri Selivanov 明确说明了这一点here:

    在我看来,目前我们正在窥视未来的时间。我们为什么不这样做

           end_time = self.time() - self._clock_resolution
    

    保证超时总是会在请求时间之后触发,而不是之前?我不知道如果我们这样做,性能会变得更糟。

    真的,让我们运行下一个程序(Windows 10 上的 Python 3.8):

    import asyncio 
    import time
    
    async def main():
        print("Timer resolution", time.get_clock_info('monotonic').resolution)
        while True:
            asyncio.create_task(asyncio.sleep(1))
    
            t0 = time.monotonic()
            await asyncio.sleep(0.1)
            t1 = time.monotonic()
    
            print(t1 - t0)
    asyncio.run(main()) 
    

    我们看到上述行为:

    Timer resolution 0.015625
    0.09299999987706542
    0.0940000000409782
    0.0940000000409782
    0.10900000017136335
    ...
    

    但是在正文的开头,我说至少时钟分辨率,因为asyncio 在协作多任务的条件下工作,并且如果有一个贪婪的协程(或许多不那么贪婪的协程) ) 不会太频繁地控制事件循环,我们有以下图片:

    import asyncio 
    import time
    
    async def calc():
        while True:
            k = 0
            for i in range(1*10**6):        
                k += i
            await asyncio.sleep(0.1)  # yield to event loop
        
    
    async def main():
        asyncio.create_task(calc())  # start greedy coroutine
        print("Timer resolution", time.get_clock_info('monotonic').resolution)
        while True:
            asyncio.create_task(asyncio.sleep(1))
    
            t0 = time.monotonic()
            await asyncio.sleep(0.1)
            t1 = time.monotonic()
    
            print(t1 - t0)
    asyncio.run(main()) 
    

    不出所料,情况正朝着延迟增加的方向发生变化:

    0.17200000025331974
    0.1559999999590218
    0.14100000029429793
    0.2190000000409782
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      相关资源
      最近更新 更多