Sanic、Fastapi 和 Fiber 简单压测对比

测试代码
Sanic:

from sanic import Sanic from sanic.response import json from sanic.request import Requestapp = Sanic("Demo Of Sanic")@app.get("/") async def test(request: Request): return json({'Hello': 'World'})if __name__ == '__main__': app.run(workers=8)

Fiber:
package mainimport ( "github.com/gofiber/fiber/v2" )func main() { app := fiber.New()app.Get("/", func(c *fiber.Ctx) error { return c.JSON(map[string]string{ "Hello": "World", }) })app.Listen(":8000") }

压测
压测使用的程序是go-stress-testing1000个并发,每个并发进行1000次请求。
每栏对应的字段为:
耗时 │并发数 │ 成功数│ 失败数 │qps│ 最长耗时 │ 最短耗时│ 平均耗时│下载字节│字节每秒│ 错误码

Sanic:
... 1s│1000│4064│0│ 4688.36│428.60│106.12│213.29│69,088│69,028│200:4064 ... 188s│1000│ 989209│0│ 5404.96│578.58│71.49│185.02│16,816,553│89,449│200:989209 189s│1000│ 995278│0│ 5409.15│578.58│71.49│184.87│16,919,726│89,522│200:995278 190s│1000│1000000│0│ 5420.32│578.58│0.40│184.49│17,000,000│89,621│200:1000000*************************结果 stat**************************** 处理协程数量: 1000 请求总数(并发数*请求数 -c * -n): 1000000 总请求时间: 189.687 秒 successNum: 1000000 failureNum: 0 tp90: 235.000 tp95: 299.000 tp99: 387.000 *************************结果 end****************************

Fiber:
... 1s│1000│4264│0│ 4944.17│428.17│103.75│202.26│72,488│72,486│200:4264 ... 160s│1000│ 991952│0│ 6367.34│428.17│87.23│157.05│16,863,184│ 105,394│200:991952 161s│1000│ 998890│0│ 6374.53│428.17│60.73│156.87│16,981,130│ 105,472│200:998890 161s│1000│1000000│0│ 6379.79│428.17│0.31│156.75│17,000,000│ 105,514│200:1000000*************************结果 stat**************************** 处理协程数量: 1000 请求总数(并发数*请求数 -c * -n): 1000000 总请求时间: 161.116 秒 successNum: 1000000 failureNum: 0 tp90: 175.000 tp95: 182.000 tp99: 198.000 *************************结果 end****************************

【Sanic、Fastapi 和 Fiber 简单压测对比】可以看出来,sanicfiber差别不大,sanic的性能几乎与fiber持平,可能是当下最高性能的 Python Web 框架,没有之一,即便是之前较为突出的异步框架fastapi也要落后于sanic
附上fastapi的结果:
... 1s│1000│3140│0│ 3868.18│397.67│98.50│258.52│53,380│52,552│200:3140 ... 239s│1000│ 991225│0│ 4254.52│557.98│87.20│235.04│16,850,825│70,505│200:991225 240s│1000│ 995799│0│ 4257.07│557.98│87.20│234.90│16,928,583│70,535│200:995799 241s│1000│1000000│0│ 4266.06│557.98│0.79│234.41│17,000,000│70,585│200:1000000*************************结果 stat**************************** 处理协程数量: 1000 请求总数(并发数*请求数 -c * -n): 1000000 总请求时间: 240.841 秒 successNum: 1000000 failureNum: 0 tp90: 279.000 tp95: 296.000 tp99: 348.000 *************************结果 end****************************

FlaskDjango等框架不在本文讨论范围之内,这二者本就不是为了高性能设计的框架,没有对比的意义。
sanic还有一个优势,就是其没有开发服务器,用sanic -w 8 main.app 运行的服务器就是生产服务器。
如果有想用 Python 开发 Web 服务器的,建议优先考虑sanic

    推荐阅读