【问题标题】:ThreadPoolExecutor vs threading.ThreadThreadPoolExecutor 与 threading.Thread
【发布时间】:2017-12-27 16:33:23
【问题描述】:

我有一个关于 ThreadPoolExecutorThread 类本身的性能的问题,在我看来,我缺乏一些基本的理解。

我有一个具有两个功能的网络 scraper。首先解析网站主页的每个图像的链接,然后从解析的链接中加载图像:

import threading
import urllib.request
from bs4 import BeautifulSoup as bs
import os
from concurrent.futures import ThreadPoolExecutor

path = r'C:\Users\MyDocuments\Pythom\Networking\bbc_images_scraper_test'
url = 'https://www.bbc.co.uk'

# Function to parse link anchors for images
def img_links_parser(url, links_list):
    res = urllib.request.urlopen(url)
    soup = bs(res,'lxml')
    content = soup.findAll('div',{'class':'top-story__image'})

    for i in content:
        try:
            link = i.attrs['style']
            # Pulling the anchor from parentheses
            link = link[link.find('(')+1 : link.find(')')]
            # Putting the anchor in the list of links
            links_list.append(link)
        except:
            # links might be under 'data-lazy' attribute w/o paranthesis
            links_list.append(i.attrs['data-lazy'])

# Function to load images from links
def img_loader(base_url, links_list, path_location):
    for link in links_list:
        try:
            # Pulling last element off the link which is name.jpg
            file_name = link.split('/')[-1]
            # Following the link and saving content in a given direcotory
            urllib.request.urlretrieve(urllib.parse.urljoin(base_url, link), 
            os.path.join(path_location, file_name))
        except:
            print('Error on {}'.format(urllib.parse.urljoin(base_url, link)))

以下代码分为两种情况:

案例 1:我正在使用多个线程:

threads = []
t1 = threading.Thread(target = img_loader, args = (url, links[:10], path))
t2 = threading.Thread(target = img_loader, args = (url, links[10:20], path))
t3 = threading.Thread(target = img_loader, args = (url, links[20:30], path))
t4 = threading.Thread(target = img_loader, args = (url, links[30:40], path))
t5 = threading.Thread(target = img_loader, args = (url, links[40:50], path))
t6 = threading.Thread(target = img_loader, args = (url, links[50:], path))

threads.extend([t1,t2,t3,t4,t5,t6])
for t in threads:
    t.start()
for t in threads:
    t.join()

上面的代码在我的机器上运行了 10 秒。

案例2:我正在使用ThreadPoolExecutor

with ThreadPoolExecutor(50) as exec:
    results = exec.submit(img_loader, url, links, path)

以上代码结果为 18 秒。

我的理解是ThreadPoolExecutor 为每个工人创建一个线程。因此,假设我将 max_workers 设置为 50 将导致 50 个线程,因此应该更快地完成工作。

有人可以解释一下我在这里缺少什么吗?我承认我在这里犯了一个愚蠢的错误,但我就是不明白。

非常感谢!

【问题讨论】:

  • 正如@hansaplast 所说,我只使用了一名工人。所以我只是更改了我的img_loader 函数以接受单个链接,然后在上下文管理器下方添加一个for 循环来处理列表中的每个链接。并将时间缩短到 3.8 秒。

标签: multithreading python-3.x threadpoolexecutor


【解决方案1】:

在案例 2 中,您将所有链接发送给一名工作人员。而不是

exec.submit(img_loader, url, links, path)

你需要:

for link in links:
    exec.submit(img_loader, url, [link], path)

我自己没试过,只是来自reading the documentation of ThreadPoolExecutor

【讨论】:

  • 是的,你完全正确。我不知道为什么我不自己尝试一下,尽管我也有想过。非常感谢你回到我身边!结果是 3.8 秒,太酷了! :)
  • @Vlad,您能否为您的问题添加正确答案。 concurrent.futures.ThreadPoolExecutorthreading 有什么区别?
【解决方案2】:

按照link 的解释,您还可以使用 executor.map 函数,而不是按照 hansaplast 的建议运行 for 循环。

with ThreadPoolExecutor() as executor:

    # Create a new partially applied function that stores the directory
    # argument.
    # 
    # This allows the download_link function that normally takes two
    # arguments to work with the map function that expects a function of a
    # single argument.
    fn = partial(download_link, download_dir)

    # Executes fn concurrently using threads on the links iterable. The
    # timeout is for the entire process, not a single call, so downloading
    # all images must complete within 30 seconds.
    executor.map(fn, links, timeout=30)

我认为它可以很容易地适应您的需求。

在回答有关 threadpoolexecutor 的问题时,我不是这方面的专家,但根据我目前阅读的文档,ThreadPoolExecutor 是一种比自己使用 Threading.Thread 更简单的方法来创建动态工作池。

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 2014-01-17
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多