Python 多線程抓取圖片效率對(duì)比
目的:
是學(xué)習(xí)python 多線程的工作原理,及通過(guò)抓取400張圖片這種IO密集型應(yīng)用來(lái)查看多線程效率對(duì)比
import requests
import urlparse
import os
import time
import threading
import Queue
path = '/home/lidongwei/scrapy/owan_img_urls.txt'
#path = '/home/lidongwei/scrapy/cc.txt'
fetch_img_save_path = '/home/lidongwei/scrapy/owan_imgs/'
# 讀取保存再文件里面400個(gè)urls
with open(path) as f :
urls = f.readlines()
urls = urls[:400]
# 使用Queue來(lái)線程通信,因?yàn)殛?duì)列是線程安全的(就是默認(rèn)這個(gè)隊(duì)列已經(jīng)有鎖)
q = Queue.Queue()
for url in urls:
q.put(url)
start = time.time()
def fetch_img_func(q):
while True:
try:
# 不阻塞的讀取隊(duì)列數(shù)據(jù)
url = q.get_nowait()
i = q.qsize()
except Exception, e:
print e
break;
print 'Current Thread Name Runing %s ... 11' % threading.currentThread().name
url = url.strip()
img_path = urlparse.urlparse(url).path
ext = os.path.splitext(img_path)[1]
print 'handle %s pic... pic url %s ' % (i, url)
res = requests.get(url, stream=True)
if res.status_code == 200:
save_img_path = '%s%s%s' % (fetch_img_save_path, i, ext)
# 保存下載的圖片
with open(save_img_path, 'wb') as fs:
for chunk in res.iter_content(1024):
fs.write(chunk)
print 'save %s pic ' % i
# 可以開多個(gè)線程測(cè)試不同效果
t1 = threading.Thread(target=fetch_img_func, args=(q, ), name="child_thread_1")
#t2 = threading.Thread(target=fetch_img_func, args=(q, ), name="child_thread_2")
#t3 = threading.Thread(target=fetch_img_func, args=(q, ), name="child_thread_3")
#t4 = threading.Thread(target=fetch_img_func, args=(q, ), name="child_thread_4")
t1.start()
#t2.start()
#t3.start()
#t4.start()
t1.join()
#t2.join()
#t3.join()
#t4.join()
end = time.time()
print 'Done %s ' % (end-start)
實(shí)驗(yàn)結(jié)果
400圖片
4線程 Done 12.443133831 3線程 Done 12.9201757908 2線程 Done 32.8628299236 1線程 Done 54.6115460396
總結(jié)
Python 自帶GIL 大鎖, 沒有真正意義上的多線程并行執(zhí)行。GIL 大鎖會(huì)在線程阻塞的時(shí)候釋放,此時(shí)等待的線程就可以激活工作,這樣如此類推,大大提高IO阻塞型應(yīng)用的效率。
相關(guān)文章
Python OpenCV學(xué)習(xí)之圖形繪制總結(jié)
在圖像的任務(wù)中,不管是圖像檢測(cè)還是圖像識(shí)別,我們都需要通過(guò)繪制圖形和繪制文字對(duì)處理的結(jié)果進(jìn)行說(shuō)明,本篇就詳細(xì)介紹下OpenCV中的圖形的繪制,感興趣的可以了解一下2022-01-01
python實(shí)現(xiàn)微信遠(yuǎn)程控制電腦
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)微信遠(yuǎn)程控制電腦的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
基于Python實(shí)現(xiàn)對(duì)Excel工作表中的數(shù)據(jù)進(jìn)行排序
在Excel中,排序是整理數(shù)據(jù)的一種重要方式,它可以讓你更好地理解數(shù)據(jù),本文將介紹如何使用第三方庫(kù)Spire.XLS?for?Python通過(guò)Python來(lái)對(duì)Excel中的數(shù)據(jù)進(jìn)行排序,需要的可以參考下2024-03-03
TensorFlow索引與切片的實(shí)現(xiàn)方法
這篇文章主要介紹了TensorFlow索引與切片的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Python實(shí)現(xiàn)五子棋人機(jī)對(duì)戰(zhàn)?和人人對(duì)戰(zhàn)
這篇文章主要介紹了Python實(shí)現(xiàn)五子棋人機(jī)對(duì)戰(zhàn)?和人人對(duì)戰(zhàn),通過(guò)定義黑白子,落子位置以及獲勝規(guī)則展開詳細(xì)內(nèi)容,需要的小伙伴可以參考一下2022-05-05
用sleep間隔進(jìn)行python反爬蟲的實(shí)例講解
在本篇文章里小編給大家整理了一篇關(guān)于用sleep間隔進(jìn)行python反爬蟲的實(shí)例講解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2020-11-11

