問題描述
為了使我的代碼更pythonic"和更快,我使用多處理"和一個映射函數來發送它a)函數和b)迭代范圍.
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.
植入的解決方案(即直接在范圍 tqdm.tqdm(range(0, 30)) 上調用 tqdm)不適用于多處理(如下面的代碼所示).
The implanted solution (i.e., call tqdm directly on the range tqdm.tqdm(range(0, 30)) does not work with multiprocessing (as formulated in the code below).
進度條顯示從0到100%(python讀取代碼時?)但并不表示map函數的實際進度.
The progress bar is displayed from 0 to 100% (when python reads the code?) but it does not indicate the actual progress of the map function.
如何顯示進度條,指示地圖"功能在哪一步?
from multiprocessing import Pool
import tqdm
import time
def _foo(my_number):
square = my_number * my_number
time.sleep(1)
return square
if __name__ == '__main__':
p = Pool(2)
r = p.map(_foo, tqdm.tqdm(range(0, 30)))
p.close()
p.join()
歡迎任何幫助或建議...
Any help or suggestions are welcome...
推薦答案
找到的解決方案:小心!由于多處理,估計時間(每個循環的迭代次數、總時間等)可能不穩定,但進度條運行良好.
Solution Found : Be careful! Due to multiprocessing, estimation time (iteration per loop, total time, etc.) could be unstable, but the progress bar works perfectly.
注意:Pool 的上下文管理器僅適用于 Python 3.3 版
Note: Context manager for Pool is only available from Python version 3.3
from multiprocessing import Pool
import time
from tqdm import *
def _foo(my_number):
square = my_number * my_number
time.sleep(1)
return square
if __name__ == '__main__':
with Pool(processes=2) as p:
max_ = 30
with tqdm(total=max_) as pbar:
for i, _ in enumerate(p.imap_unordered(_foo, range(0, max_))):
pbar.update()
這篇關于多處理:使用 tqdm 顯示進度條的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!