zoukankan      html  css  js  c++  java
  • pythonのgevent同步异步区别

     1 #!/usr/bin/env python
     2 
     3 from urllib import  request
     4 import  gevent
     5 from gevent import monkey
     6 import time
     7 
     8 monkey.patch_all() # 把当前程序所有的IO操作给我单独的做上标记。
     9 def f(url):
    10     resp = request.urlopen(url)
    11     data = resp.read()
    12     print(len(data))
    13 
    14 urls = ["https://www.python.org",
    15         "https://www.yahoo.com",
    16         "https://github.com"
    17         ]
    18 time_start = time.time()
    19 for url in urls:
    20     f(url)
    21 print("同步花费时间:",time.time()-time_start)
    22 
    23 asy_time = time.time()
    24 gevent.joinall({
    25     gevent.spawn(f,"https://www.python.org"),
    26     gevent.spawn(f,"https://www.yahoo.com"),
    27     gevent.spawn(f,"https://github.com"),
    28 })
    29 print("异步花费时间:",time.time()-asy_time)
    C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/PythonStudy/charm/01/day10/爬虫.py
    48822
    479812
    64096
    同步花费时间: 4.925281763076782
    48822
    64096
    477025
    异步花费时间: 3.1961827278137207
    
    Process finished with exit code 0
  • 相关阅读:
    洛谷P1085 不高兴的津津
    为什么要学习算法
    洛谷P1001 A+B Problem
    计算机问题求解周期
    洛谷P1000 超级玛丽游戏
    洛谷P1421 小玉买文具
    CF359D Pair of Numbers(ST+二分)
    2020.10.7
    2020.10.10
    2020.10.8
  • 原文地址:https://www.cnblogs.com/pengpengzhang/p/9585034.html
Copyright © 2011-2022 走看看