首页 > 解决方案 > 同步代码的异步性能

问题描述

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

Inreturn_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 倍以上。

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

标签: pythonpython-3.xasynchronouspython-asynciouvloop

解决方案


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


推荐阅读