繁体   English   中英

使用同步代码的 Asyncio 性能

[英]Asyncio performance with synchronous code

我创建了以下测试来检查在异步函数中运行同步代码的性能。

return_random函数可以是写日志、转储或加载 json、验证输入输出日期、调用其他函数等。

count_sync 和 count_async 变量用于跳过打开和关闭事件循环的开销。 只需计算函数内的时间。

这部分代码只是调用同步函数计数次数。

import timeit
from time import time
from random import random

count = 100
run_numbers = 100000

count_sync = 0

def return_random():
    return random()

def test():
    global count_sync
    start = time()
    for _ in range(count):
       return_random()
    count_sync += time() - start
    return

total_sunc = timeit.timeit('test()', globals=globals(), 
      number=run_numbers))

相同的代码,但现在return_random是异步函数:

import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

count_async = 0

async def return_random_async():
   return random()

async def test_async():
   global count_async
   start = time()
   for _ in range(count):
      await return_random_async()
   count_async += time() - start
   return

total_sunc = timeit.timeit('asyncio.run(test_async())', globals=globals(), number=run_numbers)

使用不同数量的调用函数和运行时间计数运行代码后,得到以下结果:

RUNNING run_numbers: 1000. CALL FUNCTIONS count: 1000
total sync:  0.12023316
total Async: 0.48369559500000003
inside def sync  0.11995530128479004
inside def Async:0.24073457717895508

RUNNING run_numbers: 100000. CALL FUNCTIONS count: 100
total sync:   1.422697458
total Async: 25.452165134999998   (!!!)
inside def sync:  1.3965537548065186
inside def Async: 2.8397130966186523

所有时间都以同步功能运行,速度快 2 倍以上。

这是否意味着没有异步功能可以更好地运行同步代码? 最好不要使用很多异步函数?

只有在真正需要时才需要使用异步函数。 示例:异步 http 库(如aiohttp 、异步驱动程序(如用于 MongoDB 的motor_asyncio等)。在其他情况下,最好使用非异步函数运行同步代码,因为它们具有您不需要的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM