Multiprocessing : use tqdm to display a progress bar

后端 未结 8 478
情深已故
情深已故 2020-12-04 07:26

To make my code more \"pythonic\" and faster, I use \"multiprocessing\" and a map function to send it a) the function and b) the range of iterations.

The implanted s

相关标签:
8条回答
  • 2020-12-04 07:45

    based on the answer of Xavi Martínez I wrote the function imap_unordered_bar. It can be used in the same way as imap_unordered with the only difference that a processing bar is shown.

    from multiprocessing import Pool
    import time
    from tqdm import *
    
    def imap_unordered_bar(func, args, n_processes = 2):
        p = Pool(n_processes)
        res_list = []
        with tqdm(total = len(args)) as pbar:
            for i, res in tqdm(enumerate(p.imap_unordered(func, args))):
                pbar.update()
                res_list.append(res)
        pbar.close()
        p.close()
        p.join()
        return res_list
    
    def _foo(my_number):
        square = my_number * my_number
        time.sleep(1)
        return square 
    
    if __name__ == '__main__':
        result = imap_unordered_bar(_foo, range(5))
    
    0 讨论(0)
  • 2020-12-04 07:50
    import multiprocessing as mp
    import tqdm
    
    
    some_iterable = ...
    
    def some_func():
        # your logic
        ...
    
    
    if __name__ == '__main__':
        with mp.Pool(mp.cpu_count()-2) as p:
            list(tqdm.tqdm(p.imap(some_func, iterable), total=len(iterable)))
    
    0 讨论(0)
提交回复
热议问题