这个代码的测试结果是:
siege 10.9.40.173:8888/asynctask?t=1 -c10 -r1 ** SIEGE 3.0.8 ** Preparing 10 concurrent users for battle. The server is now under siege.. done. Transactions: 10 hits Availability: 100.00 % Elapsed time: 10.07 secs Data transferred: 0.00 MB Response time: 9.45 secs Transaction rate: 0.99 trans/sec Throughput: 0.00 MB/sec Concurrency: 9.39 Successful transactions: 10 Failed transactions: 0 Longest transaction: 10.06 Shortest transaction: 9.05不知道为啥,这种代码的表现是,10个并发全部查询完才有一次性返回。可以说这个代码根本没有达到异步的效果。甚至比同步还差!
同步是1s的时候返回第1个请求,2s的时候返回第2个请求…
这种方式,在最后第10s的时候一次性返回10个请求,每个请求的响应时间都是10s。求高手指点一下这是为啥。
伯乐在线的文章的作者解释:
使用 yield task的方式,准确来说是协程。只是在网络IO中tornado的主线程不至于被 handler里的代码 block,单个handler还是被网络耗时任务所block的。如果并发连接比较小的情况下,很有可能其性能还不如同步的写法好。
具体以你自己的测试结果为准吧,在底层上,tornado这样的做法在IO层面上是异步的。
个人认为,使用协程跳到另一个函数去执行ping/sql操作,就阻塞在另一个函数里了,只是没有阻塞在handler的get中,对于整个程序而言,那还是被block了。。
fetch如果tornado.gen.coroutine如此不堪的话,那它还有什么用?参照官网的例子,官网例子是用来fetch的。
同步fetch class OfficialSynHandler(tornado.web.RequestHandler): def get(self): print '# in get', datetime.datetime.now() client = tornado.httpclient.HTTPClient() response = client.fetch("http://www.csdn.net/") print 'response', response self.write('ok')siege测试结果
siege 10.9.40.173:8888/officialsyn -c10 -r1 ** SIEGE 3.0.8 ** Preparing 10 concurrent users for battle. The server is now under siege.. done. Transactions: 10 hits Availability: 100.00 % Elapsed time: 2.05 secs Data transferred: 0.00 MB Response time: 0.51 secs Transaction rate: 4.88 trans/sec Throughput: 0.00 MB/sec Concurrency: 2.47 Successful transactions: 10 Failed transactions: 0 Longest transaction: 1.03 Shortest transaction: 0.15ab压测
Document Path: /officialsyn/ Document Length: 306 bytes Concurrency Level: 10 Time taken for tests: 0.016 seconds Complete requests: 10 Failed requests: 0 Non-2xx responses: 10 Total transferred: 4450 bytes HTML transferred: 3060 bytes Requests per second: 626.25 [#/sec] (mean) Time per request: 15.968 [ms] (mean) Time per request: 1.597 [ms] (mean, across all concurrent requests) Transfer rate: 272.15 [Kbytes/sec] received异步fetch
class OfficialAsynHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): print '# in get', datetime.datetime.now() client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task(client.fetch, "www.csdn.net") print 'response', response self.write('ok')