国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python 如何用map()函數(shù)創(chuàng)建多線程任務(wù)

瀏覽:11日期:2022-06-23 09:49:18

對(duì)于多線程的使用,我們經(jīng)常是用thread來創(chuàng)建,比較繁瑣. 在Python中,可以使用map函數(shù)簡化代碼。map可以實(shí)現(xiàn)多任務(wù)的并發(fā)

簡單說明map()實(shí)現(xiàn)多線程原理:

task = [‘任務(wù)1’, ‘任務(wù)2’, ‘任務(wù)3’, …]

map 函數(shù)一手包辦了序列操作、參數(shù)傳遞和結(jié)果保存等一系列的操作,map函數(shù)負(fù)責(zé)將線程分給不同的CPU。

python 如何用map()函數(shù)創(chuàng)建多線程任務(wù)

在 Python 中有個(gè)兩個(gè)庫包含了 map 函數(shù): multiprocessing 和它鮮為人知的子庫 multiprocessing.dummy.dummy 是 multiprocessing 模塊的完整克隆,唯一的不同在于 multiprocessing 作用于進(jìn)程,而 dummy 模塊作用于線程。

代碼如下:

from multiprocessing.dummy import Pool as ThreadPoolimport osimport requestsimport timeimport numpy as np# 文件夾位置filepath = r’C:UsersAdministratorDesktopceshi’pool = ThreadPool(10)#開啟線程數(shù),即一次性拋出的請(qǐng)求數(shù)time_list = []#用來計(jì)算時(shí)間xml_list = []#數(shù)據(jù)集pathDir = os.listdir(filepath)for i, allDir in enumerate(pathDir): filename = os.path.join(’%s%s’ % (filepath + ’’, allDir)) kk = open(filename, ’r’, encoding=’utf-8’).read() data = kk.encode(’utf-8’) for k in range(10): xml_list.append(data)def res(data): # 訪問目標(biāo)服務(wù)器地址 url_host = ’https://mp.csdn.net/mdeditor#’ start = time.clock() s = requests.post(url_host, data=data) end = time.clock() if s.status_code == 200: print(end-start) time_list.append(end-start) else: print(’請(qǐng)求失敗’)# 傳入的參數(shù),1為函數(shù), 2為參數(shù)result = pool.map(res, xml_list)all_arr = np.array(time_list)aver = np.mean(all_arr)variance = np.var(all_arr)mid = np.median(all_arr)min_num = np.min(all_arr)max_num = np.max(all_arr)print(’平均值 : ’+ str(aver))print(’方差 : ’ + str(variance))print(’中值 : ’ + str(mid))print(’最小值 : ’ + str(min_num))print(’最大值 : ’ + str(max_num))

個(gè)人做的小測試,如果有錯(cuò)誤的地方希望留言提出意見及建議。

補(bǔ)充:python多進(jìn)程(multiprocessing)(map)

map的基本使用:

map函數(shù)一手包辦了序列操作,參數(shù)傳遞和結(jié)果保存等一系列的操作。

from multiprocessing.dummy import Poolpoop = Pool(4) # 4代表電腦是多少核的results = pool.map(爬取函數(shù),網(wǎng)址列表)from multiprocessing.dummy import Pool as ThreadPoolimport requestsimport timekv = {’user-agent’:’Mozilla/5.0’}def getsource(url): html = requests.get(url,headers=kv)urls = []for i in range(0,41): i = i*50 newpage = ’https://tieba.baidu.com/f?kw=讀書&ie=utf-8&pn=’ + str(i) urls.append(newpage)# 單線程爬取time1 = time.time()for each in urls: print(each) getsource(each)time2 = time.time()print(’單線程耗時(shí): ’ + str(time2-time1))# 多線程爬取pool = ThreadPool(8)time3 = time.time()results = pool.map(getsource, urls)pool.close()pool.join()time4 = time.time()print(’多線程所消耗時(shí)間:’ + str(time4 - time3))

python 如何用map()函數(shù)創(chuàng)建多線程任務(wù)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 奉化市| 鄂尔多斯市| 盈江县| 遂川县| 察雅县| 汤原县| 稷山县| 巴林右旗| 麻城市| 曲阜市| 壤塘县| 全南县| 科技| 于都县| 郴州市| 屏南县| 东乡县| 巩留县| 公安县| 乐清市| 临汾市| 商城县| 横峰县| 会泽县| 东海县| 吉安市| 乡城县| 察隅县| 九寨沟县| 托克托县| 舟山市| 湘潭县| 内黄县| 高尔夫| 若羌县| 常德市| 隆德县| 当涂县| 开江县| 沙坪坝区| 通道|