您的位置:首页 > 编程语言 > Python开发

python并发处理实测

2017-12-13 11:12 260 查看
关于python的并发能力,大家有目共睹,坑是要一个个的来填的。最近有大牛推荐了multiprocessing,还说里面有个dummy的多进程包文件,很好用。实测下具体的效果吧。

先来个传统的例子,单一的任务者--消费者模式,做到了任务产生和消费的分离。

import time
import threading
import Queue
class Consumer(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self._queue=queue
def run(self):
while True:

msg=self._queue.get()
if isinstance(msg, str) and msg=='quit':
break
print 'i am threading and i recieve %s' %msg
print 'bye bye'

def Producer():
queue=Queue.Queue()
worker=Consumer(queue)
worker.start()
start_time=time.time()
while time.time()-start_time<5:
queue.put('something at %s' %time.time())
time.sleep(1)
queue.put('quit')
worker.join()

if __name__=="__main__":
Producer()


这种是单一线程执行的,性能考虑肯定不如意。下面就引入mutiprocessing

import urllib2
import time
from multiprocessing.dummy import Pool as ThreadTool
urls=["http://baidu.com","http://www.163.com",\
"http://www.tongtool.com",'http://qq.com',"http://www.jd.com",\
"http://www.python.org","http://www.python.org/about/","http://www.python.org/doc",\
'http://www.python.org/getit/']
now=time.time()
"常规写法运行时间"
results=[]
for url in urls:
result=urllib2.urlopen(url)
results.append(result)
print time.time()-now
now=time.time()
"多进程"
pool=ThreadTool(8)
result=pool.map(urllib2.urlopen,urls)
pool.close()
pool.join()
print time.time()-now
其中的 pool对象需要一些参数,但现在最紧要的就是:进程。它可以限定线程池中worker的数量。如果不填,它将采用系统的内核数作为初值.

看下最后两个的运行时间对比,

8.4880001545

2.40899991989

效果还是很明显的,至于设置的进程数的大小,根据负载机的配置来确定,选择最合适自己的大小就可以了。

在实际应用中的一个例子,应用场景是,多个测试环境,登录的密码和账户一样,要验证的测试点也一致,唯一的区别就是访问的url不一样。总结下来,就是只需要把url做成list,map调用执行函数,以及对应的参数了。具体如下

def login(url):
browser=webdriver.Chrome()
browser.get(url)
browser.find_element_by_name("username").send_keys("testuser@***l.com")
browser.find_element_by_name("password").send_keys("testuser")
browser.find_element_by_xpath("//input[@value='登 录']").click()
print browser.get_cookies()
urls=["http://10.0.0.95","http://10.0.0.96"]
now=time.time()
"线程池的方式"
pool=ThreadTool(2)
result=pool.map(login,urls)
pool.close()
pool.join()
print time.time()-now这样执行的时候,就能并发的同时去验证多个环境了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: