pythonのgevent同步异步区别

时间:2022-12-19 22:14:22
 #!/usr/bin/env python

 from urllib import  request
import gevent
from gevent import monkey
import time monkey.patch_all() # 把当前程序所有的IO操作给我单独的做上标记。
def f(url):
resp = request.urlopen(url)
data = resp.read()
print(len(data)) urls = ["https://www.python.org",
"https://www.yahoo.com",
"https://github.com"
]
time_start = time.time()
for url in urls:
f(url)
print("同步花费时间:",time.time()-time_start) asy_time = time.time()
gevent.joinall({
gevent.spawn(f,"https://www.python.org"),
gevent.spawn(f,"https://www.yahoo.com"),
gevent.spawn(f,"https://github.com"),
})
print("异步花费时间:",time.time()-asy_time)
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe D:/PythonStudy/charm/01/day10/爬虫.py
48822
479812
64096
同步花费时间: 4.925281763076782
48822
64096
477025
异步花费时间: 3.1961827278137207 Process finished with exit code 0