当前位置:网站首页>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
边栏推荐
- 807. Maintain the urban skyline
- Research Report of exterior wall insulation system (ewis) industry - market status analysis and development prospect prediction
- China exterior wall cladding (EWC) market trend report, technical dynamic innovation and market forecast
- 信息安全-安全编排自动化与响应 (SOAR) 技术解析
- Web based photo digital printing website
- C language must memorize code Encyclopedia
- Shell Scripting
- Radar equipment (greedy)
- Penetration test (1) -- necessary tools, navigation
- Common configuration files of SSM framework
猜你喜欢
(POJ - 3685) matrix (two sets and two parts)
Web based photo digital printing website
Flask框架配置loguru日志库
pytorch提取骨架(可微)
969. Pancake sorting
渗透测试 ( 2 ) --- 渗透测试系统、靶机、GoogleHacking、kali工具
“鬼鬼祟祟的”新小行星将在本周安全掠过地球:如何观看
1529. Minimum number of suffix flips
Penetration test (3) -- Metasploit framework (MSF)
Penetration test (1) -- necessary tools, navigation
随机推荐
mysql导入数据库报错 [Err] 1273 – Unknown collation: ‘utf8mb4_0900_ai_ci’
[exercise-7] crossover answers
Opencv learning log 14 - count the number of coins in the picture (regardless of overlap)
Differential (one-dimensional, two-dimensional, three-dimensional) Blue Bridge Cup three body attack
Configuration du cadre flask loguru log Library
X-Forwarded-For详解、如何获取到客户端IP
信息安全-威胁检测引擎-常见规则引擎底座性能比较
Alice and Bob (2021 Niuke summer multi school training camp 1)
渗透测试 ( 1 ) --- 必备 工具、导航
Penetration test (2) -- penetration test system, target, GoogleHacking, Kali tool
The concept of C language array
Penetration test 2 --- XSS, CSRF, file upload, file inclusion, deserialization vulnerability
Information security - threat detection - detailed design of NAT log access threat detection platform
Analyse du format protobuf du rideau en temps réel et du rideau historique de la station B
Essai de pénétration (1) - - outils nécessaires, navigation
栈的经典应用—括号匹配问题
JS call camera
Openwrt source code generation image
【高老师UML软件建模基础】20级云班课习题答案合集
Opencv learning log 24 -- Hough transform 2 (maximum interval and minimum length can be limited)