【问题标题】:Python code execution bottleneck due to SSL - How to optimimze?由于 SSL 导致的 Python 代码执行瓶颈 - 如何优化?
【发布时间】:2017-05-08 01:36:57
【问题描述】:

我想提高 Python 脚本的性能,并一直在使用 cProfile 生成性能报告:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   75   23.514    0.314   23.514    0.314 {method 'read' of '_ssl._SSLSocket' objects}
   75    8.452    0.113    8.452    0.113 {method 'do_handshake' of '_ssl._SSLSocket' objects}
   75    2.113    0.028    2.113    0.028 {method 'load_verify_locations' of '_ssl._SSLContext' objects}
   75    1.479    0.020    1.479    0.020 {method 'connect' of '_socket.socket' objects}

示例代码:

import requests
import json
from collections import defaultdict

#Added for multiprocessing
from urllib.request import urlopen
from multiprocessing.dummy import Pool as ThreadPool 

results = defaultdict(list)

# Make the Pool of workers
pool = ThreadPool(4)

# Open the urls in their own threads
# and return the results
results = pool.map(urlopen, requests.post())

  #close the pool and wait for the work to finish
pool.close()
pool.join()

for store, data in results.items():
    print('Store: {}'.format(store), end=', ')
    if data:
        for inventory in data:
            print(inventory)

【问题讨论】:

标签: python-3.x optimization


【解决方案1】:

您正在有效地测量远程网站的响应时间,这可能不是您想要的。为了最大化吞吐量(每秒发送的 HTTP 请求数或接收的数据数),您应该异步发送许多并发请求。您可以使用异步 HTTP 库,如 aiohttp 或仅使用本机 Python asyncio/asyncore。

【讨论】:

  • 我在上面添加了示例代码。我将不得不研究 aiohttp - 我不熟悉它,或者如何修改我的代码以一次发送多个请求。
  • 您可以做的最简单的事情是运行多个线程执行 requests.post()。它没有异步请求那么高效,但它仍然可以让你加速数十倍。顺便说一句,不要全速锤击 a_single 网站,如果您产生过多的负载,您的 IP 可能会被阻止。一个好的蜘蛛会轮询多个网站,每个网站都会收到缓慢的请求流。
  • 我尝试根据示例添加多处理/线程,但由于找不到使用循环的示例,因此遇到了障碍。任何指针都将不胜感激(代码的添加在上面注释)。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2012-09-24
  • 1970-01-01
  • 2014-11-25
  • 2015-07-12
相关资源
最近更新 更多