首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将tqdm与concurrent.futures一起使用?

将tqdm与concurrent.futures一起使用?
EN

Stack Overflow用户
提问于 2018-07-31 04:21:40
回答 3查看 20.3K关注 0票数 60

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

代码语言:javascript
运行
复制
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?
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-09-09 17:01:56

您可以将tqdm包装在executor中,如下所示,以跟踪进度:

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

下面是你的例子:

代码语言:javascript
运行
复制
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)

结果是这样的:

代码语言:javascript
运行
复制
16%|██▏           | 15707/100000 [00:00<00:02, 31312.54it/s]
票数 84
EN

Stack Overflow用户

发布于 2020-09-11 01:28:26

可接受答案的问题在于,ThreadPoolExecutor.map函数必须生成结果,而不是按照可用的顺序生成结果。因此,如果myfunc的第一次调用碰巧是最后一次完成,那么只有当所有调用都完成时,进度条才会立即从0%变为100%。在as_completed中使用ThreadPoolExecutor.submit会更好

代码语言:javascript
运行
复制
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)

打印:

代码语言:javascript
运行
复制
321 103041

这只是个大概的想法。根据my_iter的类型,可能无法直接将len函数直接应用于它,而不首先将其转换为列表。要点是在as_completed中使用submit

票数 39
EN

Stack Overflow用户

发布于 2020-04-28 01:19:00

最短的方法,我想:

代码语言:javascript
运行
复制
with ThreadPoolExecutor(max_workers=20) as executor:
    results = list(tqdm(executor.map(myfunc, range(len(my_array))), total=len(my_array)))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51601756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档