import gevent





import
gevent,time ##gevent 是 第三方库 from gevent import monkey from urllib import request monkey.patch_all() ## 让程序变成IO def libs(url): print('Get %s '%url) requ = request.urlopen(url) re_requ = requ.read() urls = ['https://www.python.org/', 'https://www.yahoo.com/', 'https://github.com/' ] time_star = time.time() for i in urls: libs(i) print('损耗的时间是 %s'%(time.time()-time_star)) ootime = time.time() gevent.joinall([ gevent.spawn(libs,'https://www.python.org/'), gevent.spawn(libs,'https://www.yahoo.com/'), gevent.spawn(libs,'https://github.com/'), ]) print('异步所需的时间是 %s'%(time.time()-ootime))

结果

F:\python_oldboy\Scripts\p\Scripts\python.exe F:/python_oldboy/geve/爬虫练习.py
Get https://www.python.org/
Get https://www.yahoo.com/
Get https://github.com/
损耗的时间是 10.494600296020508
Get https://www.python.org/
Get https://www.yahoo.com/
Get https://github.com/
异步所需的时间是 3.925224542617798


 

 

import gevent
##安装第三方库  gevent, 可实现 同步或者异步编程
def foo():
    print('Running in foo')  #1
    gevent.sleep(2)
    print('context switch to foo again') #4

def bar():
    print('running in bar')  #2
    gevent.sleep(1)
    print('context switch back bar') #3

gevent.joinall([
    gevent.spawn(foo),gevent.spawn(bar)
])

 

转载于:https://www.cnblogs.com/th-lyc/p/8848490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值