python多線程編程示例——圖書排名查詢案例

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ì)更明顯。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容