python web框架性能对比测试

目前比较流行的python web框架:Flask、Tornado、Snaic、FastAPI、Quart、aiohttp
如下来自github上一个性能对比图:
image.png
https://github.com/vibora-io/vibora

对于上图的测试好像是请求hello world的测试,这种方式在实际应用明显不可靠,所以我本地通过读取mysql数据方式进行了测试。

环境准备

  1. 测试环境
    python3.8
    框架对应版本:
aiohttp           3.6.2     
fastapi           0.55.1    
Flask             1.1.2     
Quart             0.12.0      
sanic             20.3.0     
tornado           6.0.4   
  1. 测试工具Jmeter
  2. 测试数据 :mysql数据库中comment表中插入了10000+条真实评论数据,后台运行时随机取500条数据进行分词,请求测试的时候用分好的词语去查询mysql(这样保证了每次数据的随机,及mysql查询的随机)
#!/usr/bin/python3
import pymysql
import jieba
import random
import json

db = pymysql.connect("xxxx","xx","xxx","xxx" )

keyword_set = set()
def init_keyword_set():
    id_list = []
    for i in range(500):
        id_list.append(str(random.randint(0,10000)))
    id_strs = ','.join(id_list)

    cursor = db.cursor(pymysql.cursors.DictCursor)
     
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT content from comment where  id in (%s) and content is not null"%id_strs)
     
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchall()
    for item in data:
        words = jieba.lcut(item['content'],cut_all=False)
        keyword_set.update([x for x in words if len(x)>1])
    print('len---------',len(keyword_set))

init_keyword_set()

def get_mysql():
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor(pymysql.cursors.DictCursor)
    keyword = keyword_set.pop()
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT id,content from comment where content like '%%%s%%' limit 10"%keyword)
     
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchall()
    # return data
    return json.dumps(data)
 
if __name__ == '__main__':
    get_mysql()
    pass
    # 关闭数据库连接
    # db.close()

测试

各个框架小调用get_mysql()查询mysql
image.png

测试结果Jmeter导出

如下表格 分别对python的几种框架进行了30QPS、200QPS、800QPS测试
image.png

表头说明(响应时间的单位均为ms):
样本:本次场景中一共完成了多少次请求
中位数:也就是说统计50%的用户响应时间
90%百分位:90%用户的响应时间
95%百分位:95%用户的响应时间
troughput:吞吐量、“吐”进去的是请求,“吐”出来的是结果,吞吐率说的是软件系统的“饭量”,即软件系统的处理能力,也就是单位时间内软件系统能够处理多少数据/事务

结果分析:

对于结果我主要看99%百分位及异常百分比2个数据(我觉得99%百分位能说明框架对与绝大对数请求的响应时间,异常百分比能说明框架的稳定性)
图中绿色表示最好 黄色次之。

  1. 单从测试来看各个框架其实并没有量级上的差别(耗时主要发生在sql操作,实际web场景其实也是这样),
  2. flask果然符合它轻量级的人设,在30QPS这种低并发的场景下表现得最优秀。
    综合来看aiohttp的性能最好。

PS Vibora运行失败没能测试:
Vibora官方说是需要python3.7+环境,但是我本地mac上3.7 3.8都有试过hello world都跑不起来 google了一大圈都没有解决,最后放弃了
image.png

总结

本次测试可能有点片面,但是也能说明些问题,tornado老牌框架表现不错,aiohttp这个后起之秀值得关注。
其实选择一个框架不单单从性能方面考虑,我们还得从它的生态、广泛度等方面考虑。

猜你喜欢

转载自www.cnblogs.com/i-love-python/p/12961515.html