python 線程池使用

來源:互聯網
上載者:User

標籤:__name__   -o   帶來   增加   線程建立   建立線程   體驗   baseurl   cond   

傳統多線程方案會使用“即時建立, 即時銷毀”的策略。儘管與建立進程相比,建立線程的時間已經大大的縮短,但是如果提交給線程的任務是執行時間較短,而且執行次數極其頻繁,那麼伺服器將處於不停的建立線程,銷毀線程的狀態。

一個線程的已耗用時間可以分為3部分:線程的啟動時間、線程體的已耗用時間和線程的銷毀時間。在多執行緒的情景中,如果線程不能被重用,就意味著每次建立都需要經過啟動、銷毀和運行3個過程。這必然會增加系統相應的時間,降低了效率。

使用線程池:
由於線程預先被建立並放入線程池中,同時處理完當前任務之後並不銷毀而是被安排處理下一個任務,因此能夠避免多次建立線程,從而節省線程建立和銷毀的開銷,能帶來更好的效能和系統穩定性。

體驗一下使用線程池實現爬蟲

在使用前需要安裝線程池類庫: 

pip install threadpool 

#!/usr/bin/env python # coding:utf-8 # @Time : 2018/4/19 16:06# @Author : chenjisheng# @File : 17zwd_sample.py# @Mail : [email protected]from bs4 import BeautifulSoupimport threadpoolimport requestsimport threadingimport datetimebaseurl = "http://hz.17zwd.com/sks.htm?cateid=0&page="# 爬蟲函數def getResponse(url):    target = baseurl + url    content = requests.get(target).text    soup = BeautifulSoup(content, ‘lxml‘)    tags = soup.find_all(‘div‘, attrs={"class": "huohao-img-container"})    for tag in tags:        imgurl = tag.find(‘img‘).get(‘data-original‘)        # print(imgurl)# 定義線程為 10 個starttime = datetime.datetime.now()pool = threadpool.ThreadPool(10)# 定義線程池的任務tasks = threadpool.makeRequests(getResponse, [str(x) for x in range(1, 11)])# 使用線程池啟動任務[pool.putRequest(task) for task in tasks]pool.wait()endtime = datetime.datetime.now()alltime = (endtime - starttime).secondsprint("線程池總耗時為: {}秒".format(alltime))# 傳統線程starttime1 = datetime.datetime.now()tasklist = [threading.Thread(target=getResponse(str(x))) for x in range(1, 11)]for i in tasklist:    i.start()for i in tasklist:    i.join()endtime1 = datetime.datetime.now()alltime1 = (endtime1 - starttime1).secondsprint("傳統線程總耗時為: {}秒".format(alltime1))if __name__ == "__main__":    pass

最後執行結果: 線程池耗時3秒,傳統線程耗時9秒;

差別還是挺大的哈;

python 線程池使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.