V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
pc10201
V2EX  ›  Python

为什么 python 多线程还要比 gevent 要快一点?

  •  
  •   pc10201 · 2014-02-19 14:50:24 +08:00 · 5363 次点击
    这是一个创建于 3719 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码如下,初学python,如有不正确的地方请大神指正
    #coding=utf-8
    import requests
    import threading
    import time
    import Queue
    geturl='http://192.168.1.41/login.php'#内部服务器地址,可以改成自己的
    xrange_num=1000#设置循环总次数
    con_num=20#设置线程数
    start=time.time()
    class testThread(threading.Thread):
    def __init__(self,queue):
    threading.Thread.__init__(self)
    self.queue = queue

    def run(self):
    while 1:
    try:
    url= self.queue.get_nowait()
    except Queue.Empty:
    raise SystemExit
    requests.get(url)

    queue = Queue.Queue()
    for x in xrange(xrange_num):
    #line = line.strip()
    queue.put(geturl)
    threads = []

    for dummy in xrange(con_num):
    t = testThread(queue)
    t.start()
    threads.append(t)

    # Wait for all threads to finish
    for thread in threads:
    thread.join()

    print time.time()-start

    import gevent
    from gevent import monkey
    monkey.patch_all()
    from gevent.pool import Pool
    import requests

    start2=time.time()
    p = Pool(con_num)
    def down(url):
    requests.get(url)

    for x in xrange(xrange_num):
    p.spawn(down, geturl)

    p.join()
    print time.time()-start2
    raw_input()
    1 条回复    2017-03-08 16:05:22 +08:00
    isofia
        1
    isofia  
       2017-03-08 16:05:22 +08:00
    竟然一个回复都没有
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   956 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 20:19 · PVG 04:19 · LAX 13:19 · JFK 16:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.