Python 多线程抓取图片效率对比
2016-02-27 00:00
996 查看
目的:
是学习python 多线程的工作原理,及通过抓取400张图片这种IO密集型应用来查看多线程效率对比
实验结果
400图片
总结
Python 自带GIL 大锁, 没有真正意义上的多线程并行执行。GIL 大锁会在线程阻塞的时候释放,此时等待的线程就可以激活工作,这样如此类推,大大提高IO阻塞型应用的效率。
Python多线程编程(五):死锁的形成
Python多线程编程(四):使用Lock互斥锁
Python中多线程及程序锁浅析
python多线程threading.Lock锁用法实例
python线程锁(thread)学习示例
Python实现简单多线程任务队列
Python多线程、异步+多进程爬虫实现代码
Python中使用Queue和Condition进行线程同步的方法
简要讲解Python编程中线程的创建与锁的使用
是学习python 多线程的工作原理,及通过抓取400张图片这种IO密集型应用来查看多线程效率对比
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个urls with open(path) as f : urls = f.readlines() urls = urls[:400] # 使用Queue来线程通信,因为队列是线程安全的(就是默认这个队列已经有锁) q = Queue.Queue() for url in urls: q.put(url) start = time.time() def fetch_img_func(q): while True: try: # 不阻塞的读取队列数据 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 # 可以开多个线程测试不同效果 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)
实验结果
400图片
4线程 Done 12.443133831 3线程 Done 12.9201757908 2线程 Done 32.8628299236 1线程 Done 54.6115460396
总结
Python 自带GIL 大锁, 没有真正意义上的多线程并行执行。GIL 大锁会在线程阻塞的时候释放,此时等待的线程就可以激活工作,这样如此类推,大大提高IO阻塞型应用的效率。
您可能感兴趣的文章:
Python多线程编程(六):可重入锁RLockPython多线程编程(五):死锁的形成
Python多线程编程(四):使用Lock互斥锁
Python中多线程及程序锁浅析
python多线程threading.Lock锁用法实例
python线程锁(thread)学习示例
Python实现简单多线程任务队列
Python多线程、异步+多进程爬虫实现代码
Python中使用Queue和Condition进行线程同步的方法
简要讲解Python编程中线程的创建与锁的使用
相关文章推荐
- 如何在Python中编写并发程序
- Python实现简单多线程任务队列
- python的else子句使用指南
- 用python写的一个wordpress的采集程序
- python学习之编写查询ip程序
- 学习python 之编写简单乘法运算题
- 学习python之编写简单乘法口诀表实现代码
- 学习python之编写简单简单连接数据库并执行查询操作
- Python数据库的连接实现方法与注意事项
- 用Python做的数学四则运算_算术口算练习程序(后添加减乘除)
- Pythont特殊语法filter,map,reduce,apply使用方法
- python PIL模块与随机生成中文验证码
- python中input()与raw_input()的区别分析
- python中map()与zip()操作方法
- python操作mysql
- [Leetcode]220. Contains Duplicate III @python
- 笨办法学python_学习笔记2
- python之干什么可以走的路线
- 《python基础教程》第一章 基础知识
- python做量化交易干货分享