显示Python多处理池映射调用的进度?

时间:2011-04-14 16:40:14

标签: python multiprocessing

我有一个脚本可以通过imap_unordered()调用成功执行多处理池任务集:

p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xrange(num_tasks))
p.close() # No more work
p.join() # Wait for completion

然而,我的num_tasks约为250,000,因此join()将主线程锁定10秒左右,我希望能够以递增的方式回显到命令行显示主进程未锁定。类似的东西:

p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xrange(num_tasks))
p.close() # No more work
while (True):
  remaining = rs.tasks_remaining() # How many of the map call haven't been done yet?
  if (remaining == 0): break # Jump out of while loop
  print "Waiting for", remaining, "tasks to complete..."
  time.sleep(2)

是否有结果对象或池本身的方法指示剩余的任务数量?我尝试使用multiprocessing.Value对象作为计数器(do_work在执行任务后调用counter.value += 1操作),但计数器在停止递增之前仅达到总值的约85%。

10 个答案:

答案 0 :(得分:68)

无需访问结果集的私有属性:

from __future__ import division
import sys

for i, _ in enumerate(p.imap_unordered(do_work, xrange(num_tasks)), 1):
    sys.stderr.write('\rdone {0:%}'.format(i/num_tasks))

答案 1 :(得分:63)

我个人最喜欢的 - 给你一个不错的进度条并完成ETA,同时运行并同时提交。

from multiprocessing import Pool
import tqdm

pool = Pool(processes=8)
for _ in tqdm.tqdm(pool.imap_unordered(do_work, tasks), total=len(tasks)):
    pass

答案 2 :(得分:20)

通过更多挖掘找到了答案:看一下__dict__结果对象的imap_unordered,我发现它有一个_index属性,随着每个任务的完成而递增。所以这适用于日志记录,包含在while循环中:

p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xrange(num_tasks))
p.close() # No more work
while (True):
  completed = rs._index
  if (completed == num_tasks): break
  print "Waiting for", num_tasks-completed, "tasks to complete..."
  time.sleep(2)

但是,我确实发现将imap_unordered替换为map_async导致执行速度更快,但结果对象有点不同。相反,map_async的结果对象具有_number_left属性和ready()方法:

p = multiprocessing.Pool()
rs = p.map_async(do_work, xrange(num_tasks))
p.close() # No more work
while (True):
  if (rs.ready()): break
  remaining = rs._number_left
  print "Waiting for", remaining, "tasks to complete..."
  time.sleep(0.5)

答案 3 :(得分:20)

我发现当我试图检查它的进展时,工作已经完成了。这对我来说很有用tqdm

pip install tqdm

from multiprocessing import Pool
from tqdm import tqdm

tasks = range(5)
pool = Pool()
pbar = tqdm(total=len(tasks))

def do_work(x):
    # do something with x
    pbar.update(1)

pool.imap_unordered(do_work, tasks)
pool.close()
pool.join()
pbar.close()

这应该适用于所有类型的多处理,无论它们是否阻止。

答案 4 :(得分:8)

我知道这是一个相当古老的问题,但是当我想跟踪python中任务池的进展时,这就是我正在做的事情。

from progressbar import ProgressBar, SimpleProgress
import multiprocessing as mp
from time import sleep

def my_function(letter):
    sleep(2)
    return letter+letter

dummy_args = ["A", "B", "C", "D"]
pool = mp.Pool(processes=2)

results = []

pbar = ProgressBar(widgets=[SimpleProgress()], maxval=len(dummy_args)).start()

r = [pool.apply_async(my_function, (x,), callback=results.append) for x in dummy_args]

while len(results) != len(dummy_args):
    pbar.update(len(results))
    sleep(0.5)
pbar.finish()

print results

基本上,您将apply_async与callbak一起使用(在这种情况下,它是将返回的值附加到列表中),因此您不必等待其他操作。然后,在while循环中,检查工作的进度。在这种情况下,我添加了一个小部件,使其看起来更好。

输出:

4 of 4                                                                         
['AA', 'BB', 'CC', 'DD']

希望它有所帮助。

答案 5 :(得分:3)

我创建了一个自定义类来创建进度打印输出。 Maby有助于:

from multiprocessing import Pool, cpu_count


class ParallelSim(object):
    def __init__(self, processes=cpu_count()):
        self.pool = Pool(processes=processes)
        self.total_processes = 0
        self.completed_processes = 0
        self.results = []

    def add(self, func, args):
        self.pool.apply_async(func=func, args=args, callback=self.complete)
        self.total_processes += 1

    def complete(self, result):
        self.results.extend(result)
        self.completed_processes += 1
        print('Progress: {:.2f}%'.format((self.completed_processes/self.total_processes)*100))

    def run(self):
        self.pool.close()
        self.pool.join()

    def get_results(self):
        return self.results

答案 6 :(得分:1)

尝试这种简单的基于队列的方法,该方法也可以与池一起使用。请注意,在启动进度条之后打印任何内容都会导致其移动,至少对于此特定进度条而言。 (PyPI的进度为1.5)

import time
from progress.bar import Bar

def status_bar( queue_stat, n_groups, n ):

    bar = Bar('progress', max = n)  

    finished = 0
    while finished < n_groups:

        while queue_stat.empty():
            time.sleep(0.01)

        gotten = queue_stat.get()
        if gotten == 'finished':
            finished += 1
        else:
            bar.next()
    bar.finish()


def process_data( queue_data, queue_stat, group):

    for i in group:

        ... do stuff resulting in new_data

        queue_stat.put(1)

    queue_stat.put('finished')  
    queue_data.put(new_data)

def multiprocess():

    new_data = []

    groups = [[1,2,3],[4,5,6],[7,8,9]]
    combined = sum(groups,[])

    queue_data = multiprocessing.Queue()
    queue_stat = multiprocessing.Queue()

    for i, group in enumerate(groups): 

        if i == 0:

            p = multiprocessing.Process(target = status_bar,
                args=(queue_stat,len(groups),len(combined)))
                processes.append(p)
                p.start()

        p = multiprocessing.Process(target = process_data,
        args=(queue_data, queue_stat, group))
        processes.append(p)
        p.start()

    for i in range(len(groups)):
        data = queue_data.get() 
        new_data += data

    for p in processes:
        p.join()

答案 7 :(得分:0)

按照Tim的建议,您可以使用tqdmimap解决此问题。我刚刚偶然发现了这个问题,并调整了imap_unordered解决方案,以便可以访问映射结果。运作方式如下:

from multiprocessing import Pool
import tqdm

pool = multiprocessing.Pool(processes=4)
mapped_values = list(tqdm.tqdm(pool.imap_unordered(do_work, range(num_tasks)), total=len(values)))

如果您不关心作业返回的值,则无需将列表分配给任何变量。

答案 8 :(得分:0)

对于正在寻找与Pool.apply_async()合作的简单解决方案的任何人:

from multiprocessing import Pool
from tqdm import tqdm
from time import sleep


def work(x):
    sleep(0.5)
    return x**2

n = 10

p = Pool(4)
pbar = tqdm(total=n)
res = [p.apply_async(work, args=(
    i,), callback=lambda _: pbar.update(1)) for i in range(n)]
results = [p.get() for p in res]

答案 9 :(得分:0)

经过一番研究,我编写了一个名为 parallelbar 的小模块。它允许您分别显示池和每个核心的整体进度。 它易于使用,并有很好的描述。

例如:

from parallelbar import progress_map
from parallelbar.tools import cpu_bench


if __name__=='__main__':
    # create list of task
    tasks = [1_000_000 + i for i in range(100)]
    progress_map(cpu_bench, tasks)