63

我有一个多线程函数,我想要一个状态栏来使用tqdm. 有没有一种简单的方法来显示状态栏ThreadPoolExecutor?令我困惑的是并行化部分。

import concurrent.futures

def f(x):
    return f**2

my_iter = range(1000000)

def run(f,my_iter):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        function = list(executor.map(f, my_iter))
    return results

run(f, my_iter) # wrap tqdr around this function?
4

3 回答 3

91

您可以tqdm围绕executor以下内容跟踪进度:

list(tqdm(executor.map(f, iter), total=len(iter))

这是您的示例:

import time  
import concurrent.futures
from tqdm import tqdm

def f(x):
    time.sleep(0.001)  # to visualize the progress
    return x**2

def run(f, my_iter):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        results = list(tqdm(executor.map(f, my_iter), total=len(my_iter)))
    return results

my_iter = range(100000)
run(f, my_iter)

结果是这样的:

16%|██▏           | 15707/100000 [00:00<00:02, 31312.54it/s]
于 2018-09-09T09:01:56.190 回答
42

已接受答案的问题在于,该ThreadPoolExecutor.map函数必须生成结果,而不是按照它们可用的顺序。因此,例如,如果第一次调用myfunc恰好是最后一次完成,则进度条将同时从 0% 变为 100%,并且仅当所有调用都完成时。ThreadPoolExecutor.submit使用with会更好as_completed

import time
import concurrent.futures
from tqdm import tqdm

def f(x):
    time.sleep(0.001)  # to visualize the progress
    return x**2

def run(f, my_iter):
    l = len(my_iter)
    with tqdm(total=l) as pbar:
        # let's give it some more threads:
        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
            futures = {executor.submit(f, arg): arg for arg in my_iter}
            results = {}
            for future in concurrent.futures.as_completed(futures):
                arg = futures[future]
                results[arg] = future.result()
                pbar.update(1)
    print(321, results[321])

my_iter = range(100000)
run(f, my_iter)

印刷:

321 103041

这只是一般的想法。根据 的类型,如果不先将其转换为列表my_iter,则可能无法直接将函数应用到它。len重点是使用submitwith as_completed

于 2020-09-10T17:28:25.640 回答
3

最简短的方式,我认为:

with ThreadPoolExecutor(max_workers=20) as executor:
    results = list(tqdm(executor.map(myfunc, range(len(my_array))), total=len(my_array)))
于 2020-04-27T17:19:00.167 回答