python多線程編程特別適用于完成相互獨立的任務,同時進行,相互之間沒有依賴性。比如,下面我們介紹的從網站中查詢每本書的排名這個任務,就非常適合應用多線程來提升效率。
1 理論分析
單線程情況下,查詢n本書的排名,需要執行n次排名查詢。
多線程情況下,同時對每一本書的排名進行查詢,無需順序執行。
2 代碼實現
2.1 單線程的代碼實現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()
運行結果分析:
Paste_Image.png
單線程用時20s。
2.2 多線程的代碼實現 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
多線程用時6s。
3 結果分析
分析結果,我們會發現,對于這種多任務不具關聯性的情況,采用多線程會明顯節省時間,效率大大提高,我們僅僅舉了一個查詢3本書的排名就省了十幾秒,如果要查更多的書,效果會更明顯。