我发现 urllib3 和请求之间没有太大区别(请求可能更快)。我会使用异步库,因为这是一个主要用例。
from gevent import monkey, spawn, joinall
monkey.patch_all()
import urllib3, certifi
from time import time
threads = []
url = 'https://www.google.com'
upool = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(), num_pools=20, block=False)
t0 = time()
for i in xrange(10000):
threads.append(spawn(upool.request,'GET',url))
x = joinall(threads)
print len(x)
print time() - t0
请注意,您可以通过将 true 添加到 block 来限制一次使用的连接数。
* 多处理更新 *
from gevent import monkey, spawn, joinall
monkey.patch_all()
import urllib3, certifi
from time import time
import gipc
worker = {}
num_threads = 1000
def fetch(num_threads, url, cpu):
print('starting {}'.format(cpu))
threads = []
upool = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(), num_pools=20, block=False)
t0 = time()
for i in xrange(num_threads):
threads.append(spawn(upool.request, 'GET', url))
x = joinall(threads)
return x, time() - t0
def count_cpus():
import multiprocessing
cpus = multiprocessing.cpu_count()
print(cpus)
return cpus
def multicore(url):
global worker
with gipc.pipe() as (r,w):
for cpu in range(count_cpus()):
worker[str(cpu)] = gipc.start_process(target=fetch, args=(num_threads, url, cpu))
for work in worker:
worker[work].join()
return worker
if __name__ == '__main__':
multicore('https://www.google.com')
for work in worker:
print worker[work]