python tornado非同步效能測試

2021-09-07 18:07:22 字數 2561 閱讀 7383

測試兩個介面

#

-*- 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

defget(self):

resp = yield

self.sleep_for_result()

self.write(resp)

@run_on_executor

defsleep_for_result(self):

time.sleep(5)

return

'非同步的hello world

' (r

'/sync

', synchandler),

(r'/async

', asynchandler),

])if

__name__ == "

__main__":

from tornado.options import

options, define

define(

"port

", default=8080, help="

跑在8080

http_server.start(1) # 程序數量

tornado.ioloop.ioloop.instance().start()

啟動tornado服務。

這裡不使用ab測試,使用更靈活的**執行緒池測試效能,使用執行緒池併發方式請求介面

#

coding=utf8

import

requests

import

time

from tomorrow import

threads

@threads(10)

deftest_sync():

print requests.get('

').content + '

' + time.strftime('

%h:%m:%s')

@threads(10)

deftest_async():

print requests.get('

').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秒能處理更多的請求。但是如果介面耗時100秒,提高併發需要設定幾十個程序幾百個執行緒來彌補,資源消耗很大,還是需要使用非同步。

python Tornado非同步與延遲任務

python tornado 非同步與延遲任務 threadpoolexecutor模組和run on exexutor裝飾器。就是建立執行緒池,用run on executor裝飾的函式即執行在其中執行緒中,從而主線程中分離出來,達到非同步的目的。tornado的ioloop.add callba...

python tornado 框架使用 (1)

1 日誌系統 common logging.py usr bin env python coding utf 8 import logging import logging.config import os from unipath import path logging.config.fileco...

python tornado實現簡單的檔案上傳功能

在web應用開發的功能中,檔案的上傳是經常會使用到的功能,本文就是利用python tornado框架,實現了乙個簡單的檔案上傳功能 tornado.httputil.httpfile物件三個屬性 1.filename檔名 2.body檔案內部實際內容 3.type檔案的型別 defget self...