python多線程編程特別適用于完成相互獨(dú)立的任務(wù),同時(shí)進(jìn)行,相互之間沒有依賴性。比如,下面我們介紹的從網(wǎng)站中查詢每本書的排名這個(gè)任務(wù),就非常適合應(yīng)用多線程來(lái)提升效率。
1 理論分析
單線程情況下,查詢n本書的排名,需要執(zhí)行n次排名查詢。
多線程情況下,同時(shí)對(duì)每一本書的排名進(jìn)行查詢,無(wú)需順序執(zhí)行。
2 代碼實(shí)現(xiàn)
2.1 單線程的代碼實(shí)現(xiàn)bookrank.py
#!/usr/bin/env python
# coding=utf-8
# import pdb
from atexit import register
from re import compile
from threading import Thread
from time import ctime
from urllib2 import urlopen as uopen
REGEX = compile('#([\d,]+) in Books')
AMZN = 'http://amazon.com/dp/'
ISBNs = {
'0132269937':'Core Python Programming',
'0132356139':'Python web Development with Djanjo',
'0137143419':'Python Fundamentals',
}
def getRanking(isbn):
page = uopen('%s%s' % (AMZN,isbn))
data = page.read()
page.close()
return REGEX.findall(data)[0]
def _showRanking(isbn):
print '- %r ranked %s' %(ISBNs[isbn],getRanking(isbn))
def main():
print 'At', ctime(), 'On Amazon...'
# pdb.set_trace()
for isbn in ISBNs:
_showRanking(isbn)
@register
def _atexit():
print 'ALL DONE at:', ctime()
if __name__ == '__main__':
main()
運(yùn)行結(jié)果分析:

Paste_Image.png
單線程用時(shí)20s。
2.2 多線程的代碼實(shí)現(xiàn) bookrank_mts.py
#!/usr/bin/env python
# coding=utf-8
# import pdb
from atexit import register
from re import compile
from threading import Thread
from time import ctime
from urllib2 import urlopen as uopen
REGEX = compile('#([\d,]+) in Books')
AMZN = 'http://amazon.com/dp/'
ISBNs = {
'0132269937':'Core Python Programming',
'0132356139':'Python web Development with Djanjo',
'0137143419':'Python Fundamentals',
}
def getRanking(isbn):
page = uopen('%s%s' % (AMZN,isbn))
data = page.read()
page.close()
return REGEX.findall(data)[0]
def _showRanking(isbn):
print '- %r ranked %s' %(ISBNs[isbn],getRanking(isbn))
def main():
print 'At', ctime(), 'On Amazon...'
# pdb.set_trace()
for isbn in ISBNs:
Thread(target=_showRanking, args=(isbn,)).start()
@register
def _atexit():
print 'ALL DONE at:', ctime()
if __name__ == '__main__':
main()

Paste_Image.png
多線程用時(shí)6s。
3 結(jié)果分析
分析結(jié)果,我們會(huì)發(fā)現(xiàn),對(duì)于這種多任務(wù)不具關(guān)聯(lián)性的情況,采用多線程會(huì)明顯節(jié)省時(shí)間,效率大大提高,我們僅僅舉了一個(gè)查詢3本書的排名就省了十幾秒,如果要查更多的書,效果會(huì)更明顯。