压测工具、文档、代码请参考 https://github.com/robertzhai/python/tree/master/tornado-basic
1.异步下载天气信息,@tornado.web.asynchonous装饰器
#rate_async.py
class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): client = tornado.httpclient.AsyncHTTPClient() client.fetch("http://www.weather.com.cn/data/sk/101010100.html" , callback=self.on_response) def on_response(self, response): body = json.loads(response.body) print body result_count = len(body['weatherinfo']) self.write(body['weatherinfo']['city']) self.finish()
2.异步下载天气信息,tornado.gen模块
class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous @tornado.gen.engine def get(self): client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task(client.fetch, "http://www.weather.com.cn/data/sk/101010100.html" ) body = json.loads(response.body) print body result_count = len(body['weatherinfo']) self.write(body['weatherinfo']['city']) self.finish()
3. sync 下载天气
class IndexHandler(tornado.web.RequestHandler): def get(self): client = tornado.httpclient.HTTPClient() response = client.fetch("http://www.weather.com.cn/data/sk/101010100.html" ) body = json.loads(response.body) print body result_count = len(body['weatherinfo']) self.write(body['weatherinfo']['city']) self.finish()
4.压测对比
压测命令:siege http://localhost:8000/ -c50 -t10s
压测结果:async 性能最高
sync
Transactions: 274 hits
Availability: 100.00 %
Elapsed time: 9.94 secs
Data transferred: 0.00 MB
Response time: 1.13 secs
Transaction rate: 27.57 trans/sec
Throughput: 0.00 MB/sec
Concurrency: 31.19
Successful transactions: 274
Failed transactions: 0
Longest transaction: 1.69
Shortest transaction: 0.05
async
Transactions: 857 hits
Availability: 100.00 %
Elapsed time: 9.74 secs
Data transferred: 0.00 MB
Response time: 0.07 secs
Transaction rate: 87.99 trans/sec
Throughput: 0.00 MB/sec
Concurrency: 5.78
Successful transactions: 857
Failed transactions: 0
Longest transaction: 1.23
Shortest transaction: 0.02
gen
Transactions: 780 hits
Availability: 100.00 %
Elapsed time: 9.59 secs
Data transferred: 0.00 MB
Response time: 0.07 secs
Transaction rate: 81.33 trans/sec
Throughput: 0.00 MB/sec
Concurrency: 5.79
Successful transactions: 780
Failed transactions: 0
Longest transaction: 1.17
Shortest transaction: 0.01