首页 > 解决方案 > 如何衡量 python 多处理 map_async 的进度?

问题描述

我曾经使用这个片段来监控多进程的进度。不过,现在 q.qsize() 停止工作并且只返回零。以前的做法有替代品q.qsize()吗?或者有没有更好的方法来做到这一点?

from multiprocessing import Pool, Manager, cpu_count

def process(args):
    '''
    Pickleable function for (parallel) processing.
    Expects a dictionary with keys:
        Mandatory:
        - 'filename': 'path to file to be processed',
        ...
        Optional:
        - 'queue': instance of multiprocessing.Manager().Queue()
    '''
    filename = args['filename']
    mode = args['mode']

    if 'queue' in args.keys():
        q = args['queue']
        q.put('filename')
return do_something_with(filename)
...


pool = Pool(processes=nthreads)
m = Manager()
q = m.Queue()

# prepare args...

results = pool.map_async(process, args)

# monitor progress
while True:
    if results.ready():
        break
    else:
        size = q.qsize()
        self.progress = int(100 * (size / self.n_files))
        time.sleep(1)
self.progress = 100

标签: pythonmultiprocessingpython-multiprocessing

解决方案


看起来您正在混淆您的池和队列。多处理池类为您处理排队逻辑,但池不是队列对象,它是池。因此,当您检查队列大小时,那里根本没有任何东西。

但是,要直接回答您的问题,您q.qsize()将始终为 0,因为您实际上并没有将任何内容排入队列。你的队列总是空的。q.put()如果这是您正在寻找的行为,您需要在队列中添加一些东西。

我所知道的任何东西都不会像您现在使用的那样与您的代码完全兼容pool.map_async。我不确定您想如何从这里处理它,但是有很多关于检查池中剩余多少项目 的问题。


推荐阅读