作为一个运维和一个比较懒的人,其实当时自学python的时候,想着只要会一些简单的能帮助自己工作自动化进行的就行,当时计算机是个神奇的学科,刚开始入门是时发现也就那会事,但是越发深入缺发现自己越发的缺乏职业安全感,因为技术日新月异,就发现从学校这个井口中跳出来的时候,自己所认为的那会事也就是个皮毛的皮毛,所以开始给自己规划技术之路,逼着自己去学习、坚持,刚开始的时候异常难受,逼着自己去思考新技术的应用领域,以及新技术的使用部署,但随着新技术带给自己的那份欣喜,比如,能很快很好的完成工作,能为自己以后走上高薪之路增加概率,所以自己开始主动接纳,主动去学习新技术,所以这时候接触到nodejs,凭着先天异步的优势,我分别用python和nodejs写了两个功能一样的脚本,执行下来却发现nodejs的异步使整个过程缩小了好几倍,所以开始嫌弃python是个慢悠悠的大蟒蛇,或者出于对异步的好奇和对python的情怀,所以开始开始在网上搜索python怎样实现异步,开始看到的是python3.5的async和await,但是发现压根不想nodejs的awync和await那样好用,隧再寻方法,功夫不负有心人,在网上看到了gevent这个第三方的python库,大概看下发现很好理解,就撸起袖子干起来了。
安装
- 安装起来很简单,就是pip install gevent就Ok了,借着安装说一下一个和安装有关的模块pqi
一句话总结,pqi是一个pip源管理更换模块,可以查看预置pip源和自己添加的pip源.
1 | $ pip install pqi |
1 | 查看预置和添加的pip源 |
测试比较
同步代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#coding:utf-8
import requests
import time
start = time.time()
urls = [
'http://www.heroku.com',
'http://www.baidu.com',
'http://www.163.com',
'http://www.sina.com',
'http://www.heroku.com',
'http://blog.csdn.net'
]
for i in urls:
print i+':'+str(requests.get(i).status_code)
end = time.time()
print "code run time is "+str(end-start)异步代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#coding:utf-8
import requests
import time
import gevent
from gevent import monkey
start = time.time()
urls = [
'http://www.heroku.com',
'http://www.baidu.com',
'http://www.163.com',
'http://www.sina.com',
'http://www.heroku.com',
'http://blog.csdn.net'
]
monkey.patch_all()
def getstatus(url):
print url+':'+str(requests.get(url).status_code)
jobs= [gevent.spawn(getstatus,url) for url in urls]
gevent.joinall(jobs)
end=time.time()
print "code run time is"+str(end-start)同比代码执行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19# zlx @ zlxdeMacBook-Pro in ~/Documents/Scripts [14:10:06]
$ python syncrequests.py
http://www.heroku.com:200
http://www.baidu.com:200
http://www.163.com:200
http://www.sina.com:200
http://www.heroku.com:200
http://blog.csdn.net:200
code run time is 8.59563589096
# zlx @ zlxdeMacBook-Pro in ~/Documents/Scripts [14:10:16]
$ python asyncrequests.py
http://www.baidu.com:200
http://www.163.com:200
http://www.sina.com:200
http://blog.csdn.net:200
http://www.heroku.com:200
http://www.heroku.com:200
code run time is2.84574198723
可以看出同一个功能,同一个网络环境,基本同一时间点,同步代码比异步代码耗时将近4倍,效率不是一般的快
控制异步个数,
假如我有10000个数据需要处理,我不肯呢过直接把这1000个数据全部丢入gevent.joinall中去执行吧,如果是请求类的数据处理,10000个异步发送出去相当于10000个并打打过去,这样不仅对请求的服务器是一种压力,而且要求程序处理数据非常快,要不就会堆积在缓存中,如果数量再大就有可能造成内存溢出,程序崩溃,对于这种境况,gevent提供了一个Pool的方法去限制异步的并发数。
1 | import socket |
对于我现在来说以上两种gevent的方法已经够我用的,如果想了解gevent的更多用法 一个看下gevent的官方文档
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/11/30/python异步编程库gevent的简单使用/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!