当前位置:网站首页>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 !


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 10

Indicates 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
Flask37.449s0/20000534.07
Flask+gunicorn4.630s0/200004319.60
Sanic10.363s0/200001929.99
Spring3.652s0/200005477.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
Flask37.449s0/20000534.07
Flask+gunicorn4.630s0/200004319.60
Sanic( After optimization )3.214s0/200006221.97
Spring3.652s0/200005477.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

原网站

版权声明
本文为[Rath mile_ LeslieWu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060920077555.html