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 1149 风铃(树形DP)
题目描述的实际是一颗二叉树,对于每个结点,要么满叉,要么无叉. 对于一种无解的简单情况,我们搜一遍树找到最浅的叶子结点1和最深的叶子结点2,如果dep[1]<dep[2]-1,则显然无解. 所以 ...
- 原 cocos2dx中毒冰冻shader
#ifdef GL_ES precision mediump float; #endif uniform sampler2D u_texture; varying vec2 v_texCoord; v ...
- [Leetcode] single number 找单个数
Given an array of integers, every element appears twice except for one. Find that single one. Note: ...
- CF993E Nikita and Order Statistics
小于x的赋值为1,否则为0 区间等于k的个数 求0~n连续的n+1个k? N<=1e5? FFT! 考虑卷积建模:用下标相加实现转移到位,数值相乘类比乘法原理! 法一: 分治,然后FFT没了 法 ...
- [NOI2008] 道路设计
link 思维题目,题目描述其实说的就是这是一个树,想到树形$dp$.若两个铁路不向交,则每个点的度都$\leq 2$.所以现在就可以搞dp了. 怎么去维护答案,容易想到设$dp(i,j,k)$为现在 ...
- Hive架构及应用介绍【链接】
原文链接:https://blog.csdn.net/a2011480169/article/details/51482799
- thrift源码阅读笔记
http://note.youdao.com/noteshare?id=3f3cf77bf70656ac626f7bf2099063c7
- stout代码分析之八:cache类
stout中实现了LRU cache.cache的成员如下: public: typedef std::list<Key> list; typedef std::tr1::unordere ...
- POJ 2976 二分
Dropping tests Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 12515 Accepted: 4387 D ...
- git branch 重命名
有时候你会有重命名一个git branch的冲动,不要怀疑,这是真的.command bellow will give u a big help,no thanks~ git branch - m o ...