这是有问题的代码(一个非常简单的爬虫),该文件是一个 url 列表,通常 > 1000。
import sys, gevent
from gevent import monkey
from gevent.pool import Pool
import httplib, socket
from urlparse import urlparse
from time import time
pool = Pool(100)
monkey.patch_all(thread=False)
count = 0
size = 0
failures = 0
global_timeout = 5
socket.setdefaulttimeout(global_timeout)
def process(ourl, mode = 'GET'):
global size, failures, global_timeout, count
try:
url = urlparse(ourl)
start = time()
conn = httplib.HTTPConnection(url.netloc, timeout = global_timeout)
conn.request(mode, ourl)
res = conn.getresponse()
req = res.read()
end = time()
bytes = len(req)
took = end - start
print mode, ourl, bytes, took
size = size + len(req)
count += 1
except Exception, e:
failures += 1
start = time()
gevent.core.dns_init()
print "spawning..."
for url in open('domains'):
pool.spawn(process, url.rstrip())
print "done...joining..."
pool.join()
print "complete"
end = time()
took = end - start
rate = size / took
print "It took %.2f seconds to process %d urls." % (took, count)
print rate, " bytes/sec"
print rate/1024, " KB/sec"
print rate/1048576, " MB/sec"
print "--- summary ---"
print "total:", count, "failures:", failures
当我改变池大小时,我得到了很多不同的速度变化:-
pool = Pool(100)
我一直在考虑编写一个算法来即时计算理想的池大小,但我不想跳进去,我想知道我是否忽略了一些东西?