python并发模块之concurrent.futures(二)
python并发模块之concurrent.futures(二)
上次我们简单的了解下,模块的一些基本方法和用法,这里我们进一步对concurrent.futures做一个了解和拓展.
上次的内容点这。
python并发模块之concurrent.futures(二)
以下载图片为例子,下面的程序是顺序下载http://www.58pic.com/newpic/28660111.html网站的24个表情 。
from requests_html import HTMLSession
import os
import time
BASE_PATH="downloads"
class Get_Image():
def __init__(self):
self.timeout=20
self.session=HTMLSession()
def getiamge(self,url):
req=self.session.get(url,timeout=self.timeout)
if req.status_code==200:
imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
for index,url in enumerate(imgurllist):
print(f"开始下载第{index+1}张图片")
self.save_image(url,index+1)
else:
print("下载失败")
def save_image(self,imgurl,index):
print(f"当前下载链接:{imgurl}")
buff=self.session.get(imgurl,timeout=self.timeout).content
file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
if not os.path.exists(file_path):
os.makedirs(file_path)
with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
fs.write(buff)
if __name__ == '__main__':
start_url="http://www.58pic.com/newpic/28660111.html"
start=time.time()
Get_Image().getiamge(start_url)
end=time.time()
print(f"顺序下载24张图片用时:{end-start}")
#运行了两次结果分别为
#顺序下载24张图片用时:14.926000356674194
#顺序下载24张图片用时:14.07800030708313
使用concurrent.futures修改成并发之后
from requests_html import HTMLSession
import os
import time
from concurrent.futures import ThreadPoolExecutor
BASE_PATH="downloads"
MAX_WORKERS = 10 #最多使用10个线程
class Get_Image():
def __init__(self):
self.timeout=20
self.session=HTMLSession()
def getiamge(self,url):
req=self.session.get(url,timeout=self.timeout)
if req.status_code==200:
imgurllist=req.html.xpath("//ul[@class='emoticon-model']/li/img/@data-big")
works=min(len(imgurllist),MAX_WORKERS)
with ThreadPoolExecutor(works) as excutor:
res=excutor.map(self.save_image,imgurllist,range(1,25))
return len(list(res))
else:
print("下载失败")
def save_image(self,imgurl,index):
print(f"当前下载链接:{imgurl}")
buff=self.session.get(imgurl,timeout=self.timeout).content
file_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),BASE_PATH)
if not os.path.exists(file_path):
os.makedirs(file_path)
with open(os.path.join(file_path,f"{index}.png"),"wb") as fs:
fs.write(buff)
if __name__ == '__main__':
start_url="http://www.58pic.com/newpic/28660111.html"
start=time.time()
Get_Image().getiamge(start_url)
end=time.time()
print(f"并发下载24张图片用时:{end-start}")
#运行了两次结果分别为
#并发下载24张图片用时:7.737000226974487
#并发下载24张图片用时:7.083999872207642
通过观察发现速度并发之后效率大大提高了。
python并发模块之concurrent.futures(二)的更多相关文章
- python并发模块之concurrent.futures(一)
Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threadin ...
- python3 线程池-threadpool模块与concurrent.futures模块
多种方法实现 python 线程池 一. 既然多线程可以缩短程序运行时间,那么,是不是线程数量越多越好呢? 显然,并不是,每一个线程的从生成到消亡也是需要时间和资源的,太多的线程会占用过多的系统资源( ...
- python并发编程之multiprocessing进程(二)
python的multiprocessing模块是用来创建多进程的,下面对multiprocessing总结一下使用记录. 系列文章 python并发编程之threading线程(一) python并 ...
- Python3【模块】concurrent.futures模块,线程池进程池
Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要 ...
- python基础-------模块与包(二)
sys模块.logging模块.序列化 一.sys模块 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时e ...
- Python命令模块argparse学习笔记(二)
argparse模块可以设置两种命令参数,一个是位置参数,一个是命令参数 位置参数 import argparse parser = argparse.ArgumentParser(descripti ...
- Python日志模块的管理(二)
日志模块可以通过封装一个类,也可以通过配置文件取管理 新建1个log.ini文件 [loggers] keys=root [handlers] keys=fileHandler,streamHandl ...
- Python学习-4.Python的模块加载(二)
1.部分函数加载 from SameFolder import printSameFolder printSameFolder() 该代码指从SameFolder.py中加载printSameFold ...
- Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures
参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...
随机推荐
- BZOJ 1211 树的计数(purfer序列)
首先考虑无解的情况, 根据purfer序列,当dee[i]=0并且n!=1的时候,必然无解.否则为1. 且sum(dee[i]-1)!=n-2也必然无解. 剩下的使用排列组合即可推出公式.需要注意的是 ...
- 【bzoj4196】[Noi2015]软件包管理器 树链剖分+线段树
题目描述 Linux用户和OSX用户一定对软件包管理器不会陌生.通过软件包管理器,你可以通过一行命令安装某一个软件包,然后软件包管理器会帮助你从软件源下载软件包,同时自动解决所有的依赖(即下载安装这个 ...
- Python 源码剖析(二)【整数对象】
二.整数对象 1.PyIntObject 2.PyIntObject 对象的创建和维护 3.Hack PyIntObject 1.PyIntObject PyIntObject的定义: [intobj ...
- PCA误差
我们知道,PCA是用于对数据做降维的,我们一般用PCA把m维的数据降到k维(k < m). 那么问题来了,k取值多少才合适呢? PCA误差 PCA的原理是,为了将数据从n维降低到k维,需要找到k ...
- lighttpd - 配置文件
转载其他网站,收藏查看! 配置文件lighttpd.conf参数详细说明的链接和选译 发表于 2010年12月22日 http://redmine.lighttpd.net/projects/ligh ...
- apply的理解和数组降维
func.apply(thisObj, [argArray] ); apply方法用来改变函数执行时的this指向,后面的参数是一个类数组对象,可以是数组,arguments,甚至一个有length属 ...
- linux内存管理及手动释放机制
inux系统中查看内存状态一般都会用到free linux的free命令中,cached和buffers的区别 Free Mem:表示物理内存统计 -/+ buffers/cached:表示物理内存的 ...
- Picture POJ - 1177 (线段树-扫描线)
A number of rectangular posters, photographs and other pictures of the same shape are pasted on a wa ...
- Codeforces Round #403 (Div. 2) B 三分 C dfs
B. The Meeting Place Cannot Be Changed time limit per test 5 seconds memory limit per test 256 megab ...
- 牛客多校第五场-D-inv
链接:https://www.nowcoder.com/acm/contest/143/D来源:牛客网 题目描述 Kanade has an even number n and a permutati ...