当前位置:网站首页>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
边栏推荐
- 【练习-8】(Uva 246)10-20-30==模拟
- Opencv learning log 24 -- Hough transform 2 (maximum interval and minimum length can be limited)
- 树莓派4B安装opencv3.4.0
- CEP used by Flink
- b站 實時彈幕和曆史彈幕 Protobuf 格式解析
- Socket communication
- [exercise-5] (UVA 839) not so mobile (balance)
- Interesting drink
- 栈的经典应用—括号匹配问题
- Opencv learning log 30 -- histogram equalization
猜你喜欢
Penetration test (2) -- penetration test system, target, GoogleHacking, Kali tool
Pyside6 signal, slot
渗透测试 ( 5 ) --- 扫描之王 nmap、渗透测试工具实战技巧合集
Maximum product (greedy)
C language is the watershed between low-level and high-level
渗透测试 ( 7 ) --- 漏洞扫描工具 Nessus
1013. Divide the array into three parts equal to and
Analysis of protobuf format of real-time barrage and historical barrage at station B
The concept of C language array
X-forwarded-for details, how to get the client IP
随机推荐
[teacher Gao UML software modeling foundation] collection of exercises and answers for level 20 cloud class
[analysis of teacher Gao's software needs] collection of exercises and answers for level 20 cloud class
【练习4-1】Cake Distribution(分配蛋糕)
PySide6 信号、槽
807. Maintain the urban skyline
信息安全-安全专业名称|CVE|RCE|POC|VUL|0DAY
Analyse du format protobuf du rideau en temps réel et du rideau historique de la station B
【练习-6】(Uva 725)Division(除法)== 暴力
(POJ - 3685) matrix (two sets and two parts)
socket通讯
b站 实时弹幕和历史弹幕 Protobuf 格式解析
Research Report on surgical fluid treatment industry - market status analysis and development prospect prediction
Opencv learning log 28 -- detect the red cup cover
[exercise -11] 4 values why sum is 0 (and 4 values of 0)
X-Forwarded-For详解、如何获取到客户端IP
1689. Ten - the minimum number of binary numbers
Penetration test 2 --- XSS, CSRF, file upload, file inclusion, deserialization vulnerability
[exercise-4] (UVA 11988) broken keyboard = = (linked list)
[exercise-6] (PTA) divide and conquer
1529. Minimum number of suffix flips