当前位置:网站首页>Is the sanic asynchronous framework really so strong? Find truth in practice
Is the sanic asynchronous framework really so strong? Find truth in practice
2022-07-06 16:10:00 【Rath mile_ LeslieWu】
Sanic Is the asynchronous framework really so strong ? Find truth in practice , Through to Sanic、Flask、Spring Three frames are tested to get the answer !
Catalog
Preface
With the gradual popularization of artificial intelligence projects , At present, the mainstream development language of artificial intelligence projects is still python, So use python As an algorithm external api Increasing demand . So here comes the question , At present, the mainstream python web The framework is mainly flask、django、fastapi etc. , But limited and python It's an analytic language , Its operation efficiency is not high on the whole ( Also trapped in the global interpreter lock GIL, Not like java The same framework to achieve real multithreading ), So the need for asynchronous frameworks arises , Then I will pass the following tests , contrast flask、sanic as well as java Of spring, Do a simple api The interface test , Generate the comparison document .
One 、Sanic What is it? ?
Sanic It's based on Python 3.5+ Of web frame , Depending on uvloop、asyncio Wait for event loops and asynchronous concurrency modules , Designed to support asynchronous and highly concurrent requests web service .
I won't make a specific description here , For details, please refer to the following link . I categorize it into two points :
① Support asynchronous and highly concurrent requests web service
② Sanic The use of and Flask Very similar
③ Build lightweight Restful API Microservices , Serve within the enterprise or team
④ uvloop You can make asyncio faster . in fact , It's at least better than nodejs、gevent And others Python Asynchronous framework is twice as fast . be based on uvloop Of asyncio The speed is almost close to Go The speed of the program .
sanic brief introduction
Two 、 Pressure measuring tool ab
ab yes Apache The pressure test tool that comes with you .ab Very practical , It's not just about Apache The server carries on the website visit stress test , You can also stress test other types of servers . such as Nginx、Tomcat、IIS etc. .
Use ab Order a stress test
ab Commands can be queried , Take a commonly used example :
ab -n 100 -c 10 http://localhost:5000-n 100 Indicates that the total number of requests is 100
-c 10 Indicates that the number of concurrent users is 10Indicates the target of the request URL
This line indicates processing 100 Requests and run simultaneously each time 10 Requests .
3、 ... and 、 testing procedure
1. Code instance :
sanic:
from sanic import Sanic
from sanic.response import text
app = Sanic("MyHelloWorldApp")
@app.get("/")
async def hello_world(request):
return text("Hello!!!")
if __name__ == '__main__':
app.run(port=5001, host='0.0.0.0',debug=False)
# The following code can also , At that time, in order to ensure code consistency , Define the return response The format of . But the speed is the same , No effect .
from sanic import Sanic
from sanic.response import json
app = Sanic("MyHelloWorldApp")
@app.get("/")
async def test(request):
return json({
"hello": "world"})
if __name__ == "__main__":
app.run(port=5001, host='0.0.0.0',debug=False)
flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello!!!"
if __name__ == '__main__':
app.run('0.0.0.0', port=5000,debug=False)
# The following code can also , At that time, in order to ensure code consistency , Define the return response The format of . But the speed is the same , No effect .
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def hello_world():
# return "Hello!!!"
resp = make_response("Hello!!!")
return resp
if __name__ == '__main__':
app.run('0.0.0.0', port=5000,debug=False)
java:
java A little , Package it jar package . The same return content .
flask Occupied port 5000,Sanic Occupy 5001,Spring Occupy 10001
2. Testing process
ab Tools
-n: namely requests, Used to specify the total number of stress tests performed
-c: namely concurrency, Used to specify the number of concurrencies
The test command is as follows , common 20000 Requests , Concurrent as 1000:
ab -n 20000 -c 1000 127.0.0.1:5000/ # Flask
ab -n 20000 -c 1000 127.0.0.1:5001/ # Sanic
ab -n 20000 -c 1000 127.0.0.1:10001/ # Spring
test result :
I won't map the test results , The content is more complex , Here we collect several important parameters for reference . The result value I use is the highest value taken three times per test . Generally, the first call of each framework will be relatively slow .
| Frame name | Time taken for tests ( Total time spent on stress testing ) | Failed requests: ( Number of failed requests ) Complete requests: ( The total number of times ) | Requests per second: ( The average number of requests per second ) Important parameter , Represents the throughput of the server |
|---|---|---|---|
| Flask | 37.449s | 0/20000 | 534.07 |
| Flask+gunicorn | 4.630s | 0/20000 | 4319.60 |
| Sanic | 10.363s | 0/20000 | 1929.99 |
| Spring | 3.652s | 0/20000 | 5477.01 |
3.Sanic: It's time to show real technology
Take a look at the test results above , Will you find out , How does it look? Sanic Also not imagined , So strong in legend ,Flask Just by using gunicorn As wsgi The server , It can also make up for the use of native web The shortcomings of service . It can give full play to the performance of the server .
After consulting the data, we found that , In fact, we didn't fill in the configuration . First Sanic Bring one with you Web The server . in the majority of cases , It is recommended to use this server to deploy Sanic application , Then just modify it app.run() Some parameters inside can be improved Sanic Performance .
Sanic Tips for improving performance
""" fast: Get the maximum CPU The easiest way to improve performance is to use fast Parameters . This will automatically create worker threads with the maximum number of cores in the system . access_log: Turn off the output access log to improve performance . """
app.run(port=5001, host='0.0.0.0',debug=False,access_log=False,fast=True)
ab Test information :
Server Software:
Server Hostname: 127.0.0.1
Server Port: 5001
Document Path: /
Document Length: 17 bytes
Concurrency Level: 100
Time taken for tests: 3.214 seconds
Complete requests: 20000
Failed requests: 0
Write errors: 0
Total transferred: 2140000 bytes
HTML transferred: 340000 bytes
Requests per second: 6221.97 [#/sec] (mean)
Time per request: 16.072 [ms] (mean)
Time per request: 0.161 [ms] (mean, across all concurrent requests)
Transfer rate: 650.15 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 6 2.9 6 18
Processing: 1 10 4.1 10 42
Waiting: 1 8 3.4 8 37
Total: 1 16 5.1 17 44
Percentage of the requests served within a certain time (ms)
50% 17
66% 18
75% 19
80% 20
90% 21
95% 23
98% 25
99% 27
100% 44 (longest request)
Final test results :
| Frame name | Time taken for tests ( Total time spent on stress testing ) | Failed requests: ( Number of failed requests ) Complete requests: ( The total number of times ) | Requests per second: ( The average number of requests per second ) Important parameter , Represents the throughput of the server |
|---|---|---|---|
| Flask | 37.449s | 0/20000 | 534.07 |
| Flask+gunicorn | 4.630s | 0/20000 | 4319.60 |
| Sanic( After optimization ) | 3.214s | 0/20000 | 6221.97 |
| Spring | 3.652s | 0/20000 | 5477.01 |
summary
Pass the above personal test ,Sanic Indeed, in terms of performance , It's really a good choice . Although this test is only a simple one get request , There are no internal asynchronous tasks involved ( After all, what we are going to test today is the framework itself , Not from the perspective of using external tools , After all, tools , You and me , Can be used .) The performance can be compared with java The framework is equal , Even a little bit ahead , It's also surprising . Besides, ,Sanic But use your own internal web The server , Failed gunicorn etc. .
however Sanic The ecology of , We still have to keep going , stay https://python.libhunt.com/, Even the specific information is incomplete , It's ridiculous .. But thankfully ,Sanic Its official website ( I inserted a link below , Baidu can't search ) Well done , There are very specific cases to explain , The most important , There are official Chinese documents to choose , Finally, there is no need for web page translation .
Sanic Official website , Baidu can't search
That's all about this test , If there are deficiencies, please give me more advice . In fact, whether it's language or not , The framework is good , It must be salted fish and cabbage , His taste , Stay enthusiastic , Do what you like to do , At the same time, we can do it well , sufficient
边栏推荐
- Borg maze (bfs+ minimum spanning tree) (problem solving report)
- Penetration test (4) -- detailed explanation of meterpreter command
- 409. Longest palindrome
- 【练习-4】(Uva 11988)Broken Keyboard(破损的键盘) ==(链表)
- 渗透测试 2 --- XSS、CSRF、文件上传、文件包含、反序列化漏洞
- Opencv learning log 13 corrosion, expansion, opening and closing operations
- Opencv learning log 27 -- chip positioning
- Penetration test (2) -- penetration test system, target, GoogleHacking, Kali tool
- Research Report of cylindrical grinder industry - market status analysis and development prospect forecast
- Penetration test (1) -- necessary tools, navigation
猜你喜欢

D - function (HDU - 6546) girls' competition

信息安全-安全编排自动化与响应 (SOAR) 技术解析

Gartner: five suggestions on best practices for zero trust network access

Suffix expression (greed + thinking)

1605. Sum the feasible matrix for a given row and column

Penetration test (2) -- penetration test system, target, GoogleHacking, Kali tool

C language is the watershed between low-level and high-level

Web based photo digital printing website

Data storage in memory & loading into memory to make the program run

TCP's three handshakes and four waves
随机推荐
2027. Minimum number of operations to convert strings
window11 conda安装pytorch过程中遇到的一些问题
栈的经典应用—括号匹配问题
信息安全-安全编排自动化与响应 (SOAR) 技术解析
Research Report of cylindrical grinder industry - market status analysis and development prospect forecast
Hdu-6025-prime sequence (girls' competition)
树莓派CSI/USB摄像头使用mjpg实现网页摄像头监控
Basic Q & A of introductory C language
[exercise-3] (UVA 442) matrix chain multiplication
Luogu P1102 A-B number pair (dichotomy, map, double pointer)
628. Maximum product of three numbers
Information security - Epic vulnerability log4j vulnerability mechanism and preventive measures
[exercise-7] (UVA 10976) fractions again?! (fraction split)
Borg maze (bfs+ minimum spanning tree) (problem solving report)
Auto. Getting started with JS
b站 實時彈幕和曆史彈幕 Protobuf 格式解析
China exterior wall cladding (EWC) market trend report, technical dynamic innovation and market forecast
Programmers, what are your skills in code writing?
860. Lemonade change
“鬼鬼祟祟的”新小行星将在本周安全掠过地球:如何观看