私は 2 つの単純なアプリを作成しました。1 つは以下のような raw wsgi アプリケーションで、もう 1 つは 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 秒あたりのリクエスト数: 1.52 [#/秒] (平均)
リクエストあたりの時間: 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 秒
1 秒あたりのリクエスト数: 502.28 [#/秒] (平均)
リクエストあたりの時間: 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 アプリを使用してより高速にするにはどうすればよいのでしょうか?