简体   繁体   English

使用同步代码的 Asyncio 性能

[英]Asyncio performance with synchronous code

I create the following test to check performance with running synchronous code in async function.我创建了以下测试来检查在异步函数中运行同步代码的性能。

In return_random function can be something like write log, dump or load json, validate in-out date, which call other functions... etc. return_random函数可以是写日志、转储或加载 json、验证输入输出日期、调用其他函数等。

count_sync and count_async variables using for skip overhead for open and close event loop. count_sync 和 count_async 变量用于跳过打开和关闭事件循环的开销。 just calculate time inside function.只需计算函数内的时间。

This part of code just call synchronous function count times.这部分代码只是调用同步函数计数次数。

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))

Same code but now return_random is asynchronous function:相同的代码,但现在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)

After running code with different numbers of call function and count of timeit running got following results:使用不同数量的调用函数和运行时间计数运行代码后,得到以下结果:

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

All times run with synchronous function faster more than 2 times.所有时间都以同步功能运行,速度快 2 倍以上。

Is it means that running synchronous code better with not async function?这是否意味着没有异步功能可以更好地运行同步代码? And preferably do not use a lot async functions ?最好不要使用很多异步函数?

You need to use async functions only when you really need.只有在真正需要时才需要使用异步函数。 Examples: asynchronous http libraries like aiohttp , asynchronous drivers like motor_asyncio for MongoDB, etc. In other cases it's better to run synchronous code with not async functions, because they have an overhead that you don't need to have.示例:异步 http 库(如aiohttp 、异步驱动程序(如用于 MongoDB 的motor_asyncio等)。在其他情况下,最好使用非异步函数运行同步代码,因为它们具有您不需要的开销。

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

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