python - 同步代码的异步性能
问题描述
我创建了以下测试来检查在异步函数中运行同步代码的性能。
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 倍以上。
这是否意味着在没有异步功能的情况下更好地运行同步代码?最好不要使用很多异步函数?
解决方案
只有在真正需要时才需要使用异步函数。示例:异步 http 库aiohttp
,如 MongoDB 等异步驱动程序等motor_asyncio
。在其他情况下,最好运行不带异步函数的同步代码,因为它们具有您不需要的开销。
推荐阅读
- rust - 为什么转移所有权后可以使用非捕获闭包?
- react-native - 如何在博览会中从服务器设置正确的图像路径并做出本机反应
- php - 如何获取消息返回 AJAX PHP JSON
- angular - 如何在不使用 XPath 的情况下读取 Protractor 表中的特定行?
- django - 使用下拉菜单测试我的网站时的 Django 问题
- php - 根据用户的id将用户重定向到不同的页面
- python - python3中的lxml问题
- amazon-web-services - 减小 EBS 根卷的大小 - Windows
- batch-file - 如何使用正则表达式使用批处理脚本搜索和替换文本
- javascript - 如何将导航添加到屏幕而不显示在抽屉中