新聞中心
異步操作在計算機軟硬件體系中是一個普遍概念,根源在于參與協(xié)作的各實體處理速度上有明顯差異。軟件開發(fā)中遇到的多數(shù)情況是CPU與IO的速度不匹配,所以異步IO存在于各種編程框架中,客戶端比如瀏覽器,服務(wù)端比如node.js。本文主要分析Python異步IO。

成都地區(qū)優(yōu)秀IDC服務(wù)器托管提供商(創(chuàng)新互聯(lián)建站).為客戶提供專業(yè)的四川聯(lián)通機房服務(wù)器托管,四川各地服務(wù)器托管,四川聯(lián)通機房服務(wù)器托管、多線服務(wù)器托管.托管咨詢專線:13518219792
Python 3.4標準庫有一個新模塊asyncio,用來支持異步IO,不過目前API狀態(tài)是provisional,意味著不保證向后兼容性,甚至可能從標準庫中移除(可能性極低)。如果關(guān)注PEP和Python-Dev會發(fā)現(xiàn)該模塊醞釀了很長時間,可能后續(xù)有API和實現(xiàn)上的調(diào)整,但毋庸置疑asyncio非常實用且功能強大,值得學(xué)習(xí)和深究。
示例
asyncio主要應(yīng)對TCP/UDP socket通信,從容管理大量連接,而無需創(chuàng)建大量線程,提高系統(tǒng)運行效率。此處將官方文檔的一個示例做簡單改造,實現(xiàn)一個HTTP長連接benchmark工具,用于診斷WEB服務(wù)器長連接處理能力。
功能概述:
每隔10毫秒創(chuàng)建10個連接,直到目標連接數(shù)(比如10k),同時每個連接都會規(guī)律性的向服務(wù)器發(fā)送HEAD請求,以維持HTTP keepavlie。
代碼如下:
- import argparse
- import asyncio
- import functools
- import logging
- import random
- import urllib.parse
- loop = asyncio.get_event_loop()
- @asyncio.coroutine
- def print_http_headers(no, url, keepalive):
- url = urllib.parse.urlsplit(url)
- wait_for = functools.partial(asyncio.wait_for, timeout=3, loop=loop)
- query = ('HEAD {url.path} HTTP/1.1\r\n'
- 'Host: {url.hostname}\r\n'
- '\r\n').format(url=url).encode('utf-8')
- rd, wr = yield from wait_for(asyncio.open_connection(url.hostname, 80))
- while True:
- wr.write(query)
- while True:
- line = yield from wait_for(rd.readline())
- if not line: # end of connection
- wr.close()
- return no
- line = line.decode('utf-8').rstrip()
- if not line: # end of header
- break
- logging.debug('(%d) HTTP header> %s' % (no, line))
- yield from asyncio.sleep(random.randint(1, keepalive//2))
- @asyncio.coroutine
- def do_requests(args):
- conn_pool = set()
- waiter = asyncio.Future()
- def _on_complete(fut):
- conn_pool.remove(fut)
- exc, res = fut.exception(), fut.result()
- if exc is not None:
- logging.info('conn#{} exception'.format(exc))
- else:
- logging.info('conn#{} result'.format(res))
- if not conn_pool:
- waiter.set_result('event loop is done')
- for i in range(args.connections):
- fut = asyncio.async(print_http_headers(i, args.url, args.keepalive))
- fut.add_done_callback(_on_complete)
- conn_pool.add(fut)
- if i % 10 == 0:
- yield from asyncio.sleep(0.01)
- logging.info((yield from waiter))
- def main():
- parser = argparse.ArgumentParser(description='asyncli')
- parser.add_argument('url', help='page address')
- parser.add_argument('-c', '--connections', type=int, default=1,
- help='number of connections simultaneously')
- parser.add_argument('-k', '--keepalive', type=int, default=60,
- help='HTTP keepalive timeout')
- args = parser.parse_args()
- logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
- loop.run_until_complete(do_requests(args))
- loop.close()
- if __name__ == '__main__':
- main()
測試與分析
硬件:CPU 2.3GHz / 2 cores,RAM 2GB
軟件:CentOS 6.5(kernel 2.6.32), Python 3.3 (pip install asyncio), nginx 1.4.7
參數(shù)設(shè)置:ulimit -n 10240;nginx worker的連接數(shù)改為10240
啟動WEB服務(wù)器,只需一個worker進程:
- # ../sbin/nginx
- # ps ax | grep nginx
- 2007 ? Ss 0:00 nginx: master process ../sbin/nginx
- 2008 ? S 0:00 nginx: worker process
啟動benchmark工具, 發(fā)起10k個連接,目標URL是nginx的默認測試頁面:
- $ python asyncli.py http://10.211.55.8/ -c 10000
nginx日志統(tǒng)計平均每秒請求數(shù):
- # tail -1000000 access.log | awk '{ print $4 }' | sort | uniq -c | awk '{ cnt+=1; sum+=$1 } END { printf "avg = %d\n", sum/cnt }'
- avg = 548
top部分輸出:
- VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- 657m 115m 3860 R 60.2 6.2 4:30.02 python
- 54208 10m 848 R 7.0 0.6 0:30.79 nginx
總結(jié):
1. Python實現(xiàn)簡潔明了。不到80行代碼,只用到標準庫,邏輯直觀,想象下C/C++標準庫實現(xiàn)這些功能,頓覺“人生苦短,我用Python”。
2. Python運行效率不理想。當連接建立后,客戶端和服務(wù)端的數(shù)據(jù)收發(fā)邏輯差不多,看上面top輸出,Python的CPU和RAM占用基本都是nginx的10倍,意味著效率相差100倍(CPU x RAM),側(cè)面說明了Python與C的效率差距。這個對比雖然有些極端,畢竟nginx不僅用C且為CPU/RAM占用做了深度優(yōu)化,但相似任務(wù)效率相差兩個數(shù)量級,除非是BUG,說明架構(gòu)設(shè)計的出發(fā)點就是不同的,Python優(yōu)先可讀易用而性能次之,nginx就是一個高度優(yōu)化的WEB服務(wù)器,開發(fā)一個module都比較麻煩,要復(fù)用它的異步框架,簡直難上加難。開發(fā)效率與運行效率的權(quán)衡,永遠都存在。
3. 單線程異步IO v.s. 多線程同步IO。上面的例子是單線程異步IO,其實不寫demo就知道多線程同步IO效率低得多,每個線程一個連接?10k個線程,僅線程棧就占用600+MB(64KB * 10000)內(nèi)存,加上線程上下文切換和GIL,基本就是噩夢。
ayncio核心概念
以下是學(xué)習(xí)asyncio時需要理解的四個核心概念,更多細節(jié)請看<參考資料>
1. event loop。單線程實現(xiàn)異步的關(guān)鍵就在于這個高層事件循環(huán),它是同步執(zhí)行的。
2. future。異步IO有很多異步任務(wù)構(gòu)成,而每個異步任務(wù)都由一個future控制。
3. coroutine。每個異步任務(wù)具體的執(zhí)行邏輯由一個coroutine來體現(xiàn)。
4. generator(yield & yield from) 。在asyncio中大量使用,是不可忽視的語法細節(jié)。
參考資料
1. asyncio – Asynchronous I/O, event loop, coroutines and tasks, https://docs.python.org/3/library/asyncio.html
2. PEP 3156, Asynchronous IO Support Rebooted: the "asyncio” Module, http://legacy.python.org/dev/peps/pep-3156/
3. PEP 380, Syntax for Delegating to a Subgenerator, http://legacy.python.org/dev/peps/pep-0380/
4. PEP 342, Coroutines via Enhanced Generators, http://legacy.python.org/dev/peps/pep-0342/
5. PEP 255, Simple Generators, http://legacy.python.org/dev/peps/pep-0255/
6. asyncio source code, http://hg.python.org/cpython/file/3.4/Lib/asyncio/
當前題目:快來學(xué)學(xué)Python異步IO,輕松管理10k+并發(fā)連接
瀏覽地址:http://www.fisionsoft.com.cn/article/dhiggjd.html


咨詢
建站咨詢
