Jas*_*son 1 python io asynchronous network-programming gevent
这是有问题的代码(一个非常简单的爬虫),该文件是一个 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
Run Code Online (Sandbox Code Playgroud)
当我改变池大小时,我得到了很多不同的速度变化:-
pool = Pool(100)
Run Code Online (Sandbox Code Playgroud)
我一直在考虑编写一个算法来即时计算理想的池大小,但我想知道我是否忽略了一些东西,而不是跳进去?
任何并行处理要么受 CPU 限制,要么受 IO 限制。从您的代码的性质来看,看起来在池的较小大小时它将受到 IO 限制。具体来说,它将受接口带宽的限制,也可能受系统可以承受的同时打开的套接字数量的限制(想想这里的某些版本的 Windows,我已经在不止一次的情况下设法用完了可用的套接字)。当您增加池大小时,该进程可能会开始倾向于受 CPU 限制(特别是如果您有更多的数据处理未在此处显示)。要将池大小保持在最佳值,您需要监视所有这些变量的使用情况(打开套接字的数量、进程的带宽利用率、CPU 利用率等)。您可以通过在运行爬网程序时分析指标并对池大小进行必要调整来手动执行此操作,也可以尝试自动执行此操作。在 Python 中是否可以实现类似的事情是另一回事。
| 归档时间: |
|
| 查看次数: |
1609 次 |
| 最近记录: |