为什么python gevent比串行慢?

时间:2012-02-05 12:22:53

标签: python gevent urlopen

我使用gevent进行并发下载 基于this示例,这是代码:

import gevent
from gevent import monkey

urls = ['https://www.djangoproject.com/','http://www.nytimes.com/','http://www.microsoft.com']
monkey.patch_all()

import urllib2
from datetime import datetime

def print_head(url):
    print ('Starting %s' % url)
    data = urllib2.urlopen(url).read()   
    print ('%s: %s bytes: %r' % (url, len(data), data[:50]))

startTime = datetime.now()
jobs = [gevent.spawn(print_head, url) for url in urls]
gevent.joinall(jobs)
totalTime = datetime.now() - startTime
print "Total time: %s" % totalTime

我的问题是上面的代码需要比串行版本更长的时间,并且在大多数情况下它会超时。这是更快的串行版本:

import urllib2
from datetime import datetime

urls = ['https://www.djangoproject.com/','http://www.nytimes.com/','http://www.microsoft.com']

def print_head(url):
    print ('Starting %s' % url)
    data = urllib2.urlopen(url).read()
    print ('%s: %s bytes: %r' % (url, len(data), data[:50]))

startTime = datetime.now()    
for url in urls:
    try:
        print_head(url)
    except:
        print 'ops EXCEPTION :('

totalTime = datetime.now() - startTime
print "Total time: %s" % totalTime

1 个答案:

答案 0 :(得分:1)

OK
问题是旧的gevent包 我刚刚卸载旧的并安装了来自here的新版本,正如@reclosedev指出的那样。
现在工作正常。