1. 程式人生 > >python tornado異步性能測試

python tornado異步性能測試

test 性能 out PE pytho tps syn color ret

測試兩個接口

# -*- coding:utf-8 -*-

import time
import tornado.web
import tornado.gen
import tornado.ioloop
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor


class SyncHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        time.sleep(
5) # sleep用來簡單指代某個耗時的io操作 self.write("同步的Hello World") class AsyncHandler(tornado.web.RequestHandler): executor = ThreadPoolExecutor(5) @tornado.gen.coroutine def get(self): resp = yield self.sleep_for_result() self.write(resp) @run_on_executor
def sleep_for_result(self): time.sleep(5) return 異步的Hello World application = tornado.web.Application([ (r/sync, SyncHandler), (r/async, AsyncHandler), ]) if __name__ == "__main__": from tornado.options import options, define define("port", default=8080, help="
跑在8080", type=int) http_server = tornado.httpserver.HTTPServer(application) http_server.bind(options.port) http_server.start(1) # 進程數量 tornado.ioloop.IOLoop.instance().start()

啟動tornado服務。

這裏不使用ab測試,使用更靈活的代碼線程池測試性能,使用線程池並發方式請求接口

#coding=utf8
import requests
import time
from tomorrow import threads

@threads(10)
def test_sync():
    print requests.get(http://127.0.0.1:8080/sync).content +          + time.strftime(%H:%M:%S)

@threads(10)
def test_async():
    print requests.get(http://127.0.0.1:8080/async).content +          + time.strftime(%H:%M:%S)


[test_sync() for i in range(100)]

#[test_async() for i in range(100)]

同步方式測試如下:

技術分享圖片

看以看到,10線程請求同步接口時候,是每隔5秒才能領處理完成一個請求。程序中設置的tornado進程是1,如果把tornado服務的進程數量提高為4,每5秒也能處理4個同步請求。

異步方式測試如下:

技術分享圖片

看以看到,10線程請求異步接口時候,是每隔5秒能處理5個請求,因為代碼中設置的ThreadPoolExecutor(5)數量是5。如果設置為8,那麽每5秒可以處理8個請求。

在做聯通 央行征信基於用戶授權的登錄系統時候,需要校驗用戶提交的賬號密碼驗證碼,加上使用代理ip時間很不穩定,校驗用戶提交的賬號密碼是否能夠登錄三方網站時候需要大量時間,就需要使用tornado這種異步方式了,不然用戶提交賬號密碼後需要很長時間才能得到反饋,用戶體驗就很糟糕。

如果使用django的,使用自帶服務,每5秒能處理1個請求,其他的請求都必須等待上一個請求結束,才能被處理。

但django使用uwsgi部署,不會像自帶服務表現這麽差,使用uwsgi部署時候一般都會設置進程數量和線程數量,部署後每5秒能處理更多的請求。

python tornado異步性能測試