python并行化介绍及使用 Pool
来源:互联网 发布:python 入门教程pdf 编辑:程序博客网 时间:2024/06/06 02:36
本篇将要介绍python的并行化,及简单的应用。
主要介绍map函数的使用,一手包办了序列操作、参数传递和结果保存等一系列的操作。
首先是引入库:
from multiprocessing.dummy import Pool
pool=Pool(4)
results=pool.map(爬取函数,网址列表)
本文将一个简单的例子来看一下如何使用map函数以及这种方法与普通方法的对比情况。
import timefrom multiprocessing.dummy import Pooldef getsource(url): html=requests.get(url)urls=[]for i in range(1,21): newpage='http://tieba.baidu.com/p/3522395718?pn='+str(i) urls.append(newpage)timex=time.time() #测试一for i in urls: getsource(i)print (time.time()-timex)#这里是输出的结果:#10.2820000648 time1=time.time() #测试二pool=Pool(4)results=pool.map(getsource,urls)pool.close()pool.join()print (time.time()-time1)#这里是输出结果:#3.23600006104
对比以上两种方法,可以很明显地看出 测试二比测试一要快很多。
对程序做一下解释:
测试一种
for i in urls:
getsource(i) #使程序一直遍历urls列表中的网址,然后循环调用getsource函数
测试二中:
pool=Pool(4) #声明了4个线程数量,这里的个数根据你电脑的CPU个数来定。
results=pool.map(getsource,urls) #这里使用map函数,并且函数的参数为自定义函数名称,以及函数中的参数(这里为一个列表)
pool.close() #关闭pool对象
pool.join() #join函数的主要作用是等待所有的线程(4个)都执行结束后
print (time.time()-time1) #输出所用时间差
列举Pool的其他应用函数:
from multiprocessing import Pooldef f(x): #定义一个自定义函数f return x*xif __name__ == '__main__': pool = Pool(processes=4) # start 4 worker processes result = pool.apply_async(f, (10,)) # 评估"f(10)" asynchronously print result.get(timeout=1) #限定反应时间为1 通过get函数取得result的结果 print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" it = pool.imap(f, range(10)) #使用imap函数执行自定义函数 print it.next() # prints "0" 使用next函数一个一个地取得it的执行结果 print it.next() # prints "1" print it.next(timeout=1) # prints "4" unless your computer is *very* slow import time result = pool.apply_async(time.sleep, (10,)) print result.get(timeout=1) # raises TimeoutError
1 0
- python并行化介绍及使用 Pool
- python multiprocessing dummy Pool 使用
- memory pool 原理及使用
- memory pool 原理及使用
- memory pool 原理及使用
- python中multiprocessing.pool函数介绍<转>
- python中multiprocessing.pool函数介绍
- 并行计算机及并行计算环境之初步介绍
- python 进程池1 - Pool使用简介
- python多进程中使用pool
- python 使用Pool,并需要关注结果
- python多进程中使用pool
- Python并行化
- 【python】Redis介绍及简单使用
- Jedis Pool使用原理及源码
- [python] pool
- 使用 MPI for Python 并行化遗传算法
- Tomcat 中的 JDBC Pool及配置参数的介绍
- 关于Session的机制,实现方式和安全、单点故障问题
- 【linux】ubuntu下navicat for mysql安装
- CSU 残缺的棋盘 (BFS)
- mfc cef
- 存储过程
- python并行化介绍及使用 Pool
- android studio跨应用启动service
- tomcat远程调试
- and5.1PowerManagerService深入分析(一) PMS的初始化以及低功耗模式
- CentOS修改时区以及同步时间
- hibernate注解(annoation)使用id主键生成策略
- USB总线驱动程序
- Gradle – Spring 4 MVC Hello World Example – Annotation
- 极光推送指南,直接加到项目里