我對python很陌生。我需要使用下面的函數來模擬雨水罐一個簡單的水平衡:多處理或多線程我的功能如何?
def rain_tank_model(rain, water_demand,roof_area, tank_size, household_name):
# rain and water_demand time series are numpy arrays with over than 8 million recordings.
# each houshold has installed a rain tank with a specific size
v = [] # water volume in tanks
spill = [] # amount of water spills from rain tank
unmet_demand = [] # amount of unmet water demand
volume = 0.0 # stored volume at the start of the simulation
for i in range(len(rain)):
volume += rain[i] * roof_area - water_demand[i]
if volume < 0. : #volume cannot be negative
unmet_demand.append(volume * -1)
volume = 0
v.append(volume)
spill.append(0.)
if volume > tank_size: #water should spill from the tank
spill.append(volume - tank_size)
volume = tank_size
v.append(volume)
unmet_demand.append(0.)
else:
spill.append(0.)
v.append(volume)
unmet_demand.append(0.)
file = open(str(household_name)+".txt", 'w')
for i in range(len(v)):
line =str(v[i])+"\t"+str(spill[i])+"\t"+str(unmet_demand[i])+"\n"
file.write(line)
file.close()
我需要50000個房子在運行該函數都有一個特定的雨槽尺寸,屋頂面積和水需求的時間序列。我可以通過將函數放入循環並遍歷房屋來實現此目的。由於每個模擬是完全獨立的(他們只需要訪問相同的輸入雨陣),我想也許我可以在python中使用多線程或多處理來加速模擬。我讀了他們之間的差異,但不知道我應該使用哪一個。
我嘗試了多處理(水池和地圖功能)來並行簡化版本的功能,只需要雨量爲numpy的數組作爲輸入(假設水箱尺寸和屋頂面積對於每個房屋和水需求是相同的總是不變的,簡化的原因是我不明白如何引入多個參數,我有20個房子可以模擬,循環方法比多處理方法快得多,我嘗試了從2到20個不同數量的池。我嘗試使用管理選項來共享流程之間的雨量數據,但沒有成功。我讀了很多,但它們非常先進,難以理解。請多多關注如何平行化函數或任何類似的參考例子
有沒有簡單的方法可以判斷哪一個是我的功能? –
正如我可以看到你不執行任何IO操作,如文件下載/上傳/等。所以我會去多處理。 – vovaminiof
我現在明白你的解釋。根據您提供的較長答案,每個進程都有自己的RAM。這是否意味着每個進程都會創建自己的輸入數據副本?如果是,是否有共享輸入數據(如全局參數)? –