我写了两个简单的应用程序,一个是像下面这样的原始 wsgi 应用程序,另一个是用 Flask 构建的,它们都运行在 gevent wsgi 服务器上。
当应用程序中没有网络连接时,如我所料,原始 wsgi 应用程序比烧瓶应用程序更快,但是当应用程序中有一些网络连接时,原始 wsgi 应用程序比烧瓶应用程序慢得多。
生的
import json
from gevent import monkey
monkey.patch_all() # monkey patch for both apps
import pymysql
conn = pymysql.connect(host=HOST,port=PORT,...,cursorclass=pymysql.cursors.DictCursor)
import requests
def application(environ, start_response):
# database connection
cur = conn.cursor()
cur.execute('select * from food')
res = cur.fetchall()
# requests
resp = requests.get('http://www.baidu.com')
start_response('200 OK', [('Content-Type', 'application')])
return json.dumps(res)
# return resp.content
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 8080), application)
http_server.serve_forever()
烧瓶
from gevent import monkey
monkey.patch_all()
import json
from flask import Flask
app = Flask(__name__)
conn = pymysql.connect(host=HOST,port=PORT,...,cursorclass=pymysql.cursors.DictCursor)
@app.route('/')
def index():
# database connection
cur = conn.cursor()
cur.execute('select * from food')
res = cur.fetchall()
# requests
resp = requests.get('http://www.baidu.com')
return json.dumps(res), 200
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 8080), app)
http_server.serve_forever()
我ab用来做基准测试:
$ ab -c10 -n10000 http://127.0.0.1:8080/
这是原始的 wsgi 应用程序结果:
并发级别:10
测试时间:306.216 秒
每秒请求数:1.52 [#/sec](平均值)
每个请求的时间:6585.299 [ms](平均)
每个请求的时间:658.530 [ms](平均,所有并发请求)
连接时间(毫秒)
最小值平均值[+/-sd] 中值最大值
连接:0 0 0.4 0 7
处理:1084 6499 3050.3 5951 15963
等待:96 5222 3051.4 4577 15096
总计:1085 6500 3050.2 5951 15963
特定时间内服务的请求百分比(毫秒)
50% 5938
66% 7584
75% 8597
80% 9186
90% 10829
95% 12033
98% 13209
99% 14722
100% 15963(最长请求)
和烧瓶应用程序的:
并发级别:10
测试时间:19.909 秒
每秒请求数:502.28 [#/sec](平均)
每个请求的时间:19.909 [ms](平均值)
每个请求的时间:1.991 [ms](平均值,所有并发请求)
连接时间(毫秒)
最小值平均值[+/-sd] 中值最大值
连接:0 0 0.0 0 2
处理:3 20 9.0 19 87
等待:2 20 8.9 19 86
总计:3 20 9.0 19 87
特定时间内服务的请求百分比(毫秒)
50% 19
66% 23
75% 25
80% 27
90% 31
95% 36
98% 41
99% 45
100% 87(最长请求)
所以我想知道烧瓶做了什么,我可以做些什么来更快地使用没有框架的简单 wsgi 应用程序?