【问题标题】:how to Improve The performance of code python?如何提高代码python的性能?
【发布时间】:2022-01-05 08:36:20
【问题描述】:

目前在我的代码中,我正在下载 pdf(1 页有 10 个 pdf),它有大约 900 页,所以目前我正在使用 9000 个 pdf threading,它在 1 小时内需要 1400 个 pdf,请帮助改进我的代码

  import requests
from bs4 import BeautifulSoup as bs
from concurrent.futures import ThreadPoolExecutor


def writepdf(k, v):
    path = r"C:\Users\deepak jain\Desktop\spectra"
    with requests.Session() as session:
        with open(f'{path}/{k}.pdf', 'wb') as f:
            with session.get(v, stream=True) as r:
                for data in r.iter_content():
                    f.write(data)

def main():
    with requests.Session() as s:
        current_page = 1
        end_number = 900
        threads = []
        with ThreadPoolExecutor() as executor:
            while current_page <= end_number:
                r = s.get(f'https://bidplus.gem.gov.in/bidlists?bidlists&page_no={current_page}')
                r.raise_for_status()
                soup = bs(r.content, 'lxml')
                for i in soup.select('.bid_no > a'):
                    k = i.text.strip().replace('/', '_')
                    v = f'https://bidplus.gem.gov.in{i["href"]}'
                    threads.append(executor.submit(writepdf, k, v))
                if current_page == 1:
                    num_pages = int(soup.select_one('.pagination li:last-of-type > a')['data-ci-pagination-page'])
                    end_number = min(end_number, num_pages)
                current_page += 1
            for t in threads:
                t.result()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 在这个例子中我没有看到任何线程的使用。
  • 您有两个部分正在执行请求,但第一个部分仍在按顺序完成,因此可以通过线程化来完成一些改进。
  • 另外,我已经完成了足够多的异步操作,知道如何告诉你这样做,但我知道这种类型的 Web 请求模式非常适合它,并且可能比线程更高效。

标签: python python-3.x multithreading performance asynchronous


【解决方案1】:

IIUC,您有许多页面包含指向 pdf 文件的链接。您的主线程解析页面,并且一些或工作线程下载 pdf 文件。

您使用的 ThreadPoolExecutor 看起来很合理。

一见钟情的可能改进:

  • 在每一页之后等待所有工作线程的结束(因为for t in threads 循环在主循环内)。除非您有充分的理由,否则您应该只在主循环结束时等待(即将for t in threads 循环移到主循环之外)
  • 您当前使用ThreadPoolExecutor 中的默认线程数。从 Internet 下载文件时,HTTP 协议引起的延迟可能会很高,我会尝试明确地给出该线程数并将其调整为最佳值。默认值为 5 * 处理器数量,通常以 5 结束。您可以尝试值 5、10、15 和 20(最终更多...),看看是否有改进。请注意,某些站点可能会将来自同一源地址的大量并行下载视为攻击,因此请准备好面对具有高值的连接错误。如果发生这种情况,请稍等片刻,然后使用较低的值重试。

【讨论】:

  • 能否请您编辑带有注释的代码以提供帮助
猜你喜欢
  • 2016-04-12
  • 2016-11-27
  • 2016-06-20
  • 2016-01-14
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多