Sanic , Fastapi都是优秀的python web异步框架,找了半天没找到靠谱的性能对比测试,只能自己做一个。

测试内容:纯get请求、异步ORM读

测试工具:WRK

测试代码:由于两者代码非常相似,本文就直接放上fastapi的代码demo了。

1、纯get请求 压测:

1.1 :代码

代码demo

1.2 : 结果

1.2.1 Sanic

Running 30s test @ http://0.0.0.0:7006/

4 threads and 1000 connections

Thread Stats  Avg      Stdev    Max  +/- Stdev

Latency    6.26ms    5.01ms  82.78ms  85.31%

Req/Sec    9.85k    7.36k  23.68k    50.08%

Latency Distribution

50%    4.27ms

75%    7.64ms

90%  13.17ms

99%  24.40ms

1176945 requests in 30.08s, 126.83MB read

Socket errors: connect 751, read 25, write 0, timeout 0

Requests/sec:  39131.24

Transfer/sec:      4.22MB

1.2.2 Fastapi

Running 30s test @ http://0.0.0.0:7000/index

4 threads and 1000 connections

Thread Stats  Avg      Stdev    Max  +/- Stdev

Latency    52.14ms  25.04ms 209.52ms  67.22%

Req/Sec    4.07k    0.88k    6.78k    71.38%

Latency Distribution

50%  49.73ms

75%  69.48ms

90%  84.76ms

99%  118.72ms

486736 requests in 30.04s, 65.91MB read

Socket errors: connect 0, read 1006, write 2, timeout 0

Requests/sec:  16202.60

Transfer/sec:      2.19MB

2、异步ORM读 压测:

2.1.1 Sanic

Running 30s test @ http://0.0.0.0:7005/testdb

4 threads and 1000 connections

Thread Stats  Avg      Stdev    Max  +/- Stdev

Latency    66.76ms  57.26ms 558.07ms  77.71%

Req/Sec    0.94k  384.55    1.84k    53.17%

Latency Distribution

50%  44.23ms

75%  108.09ms

90%  143.02ms

99%  247.15ms

111825 requests in 30.07s, 14.40MB read

Socket errors: connect 751, read 108, write 0, timeout 0

Requests/sec:  3719.34

Transfer/sec:    490.34KB

2.1.2 Fastapi

Running 30s test @ http://0.0.0.0:7000/testdb

4 threads and 1000 connections

Thread Stats  Avg      Stdev    Max  +/- Stdev

Latency  454.12ms  483.01ms  5.60s    86.84%

Req/Sec  699.22    153.92    1.38k    75.95%

Latency Distribution

50%  376.73ms

75%  636.51ms

90%    1.06s

99%    2.17s

82939 requests in 30.10s, 10.69MB read

Socket errors: connect 0, read 659, write 0, timeout 0

Non-2xx or 3xx responses: 379

Requests/sec:  2755.36

Transfer/sec:    363.74KB

3 结论

3.1 纯性能sanic大约是fastapi的2.5倍,sanic单机并发接近 4万 Requests/sec,而fastapi只有1.6万。

3.2 使用异步ORM进行数据库读时,瓶颈更多在数据库方面,但同样条件下,fastapi性能仍然比sanic略低,大约为sanic并发性能的0.7倍。

4 感言

python3.6版本以后web的性能真的是可比Golang了(实测sanic比go的gin框架性能约低一半,但仍处于一个数量级),限制服务器性能的更多时数据库和带宽,正常一个带数据库读写的api接口并发能到3000已经很牛了,无论哪个框架性能都过剩了。

文章来源于互联网:Sanic vs Fastapi 性能对比

发表评论