我有一個亂數串列,我想使用multiprocessing獲得最大的數字。
這是我用來生成串列的代碼:
import random
randomlist = []
for i in range(100000000):
n = random.randint(1,30000000)
randomlist.append(n)
要使用串行程序獲得最大數字:
import time
greatest = 0 # global variable
def f(n):
global greatest
if n>greatest:
greatest = n
if __name__ == "__main__":
global greatest
t2 = time.time()
greatest = 0
for x in randomlist:
f(x)
print("serial process took:", time.time()-t2)
print("greatest = ", greatest)
這是我嘗試使用多處理獲得最大數量的嘗試:
from multiprocessing import Pool
import time
greatest = 0 # the global variable
def f(n):
global greatest
if n>greatest:
greatest = n
if __name__ == "__main__":
global greatest
greatest = 0
t1 = time.time()
p = Pool() #(processes=3)
result = p.map(f,randomlist)
p.close()
p.join()
print("pool took:", time.time()-t1)
print("greatest = ", greatest)
這里的輸出是0,很明顯沒有全域變數。如何在不影響性能的情況下解決此問題?
uj5u.com熱心網友回復:
正如@Barmar 所建議的那樣,將您randomlist分成塊,然后從每個塊中處理區域最大值,最后從local_maximum_list以下計算全域最大值:
import multiprocessing as mp
import numpy as np
import random
import time
CHUNKSIZE = 10000
def local_maximum(l):
m = max(l)
print(f"Local maximum: {m}")
return m
if __name__ == '__main__':
randomlist = np.random.randint(1, 30000000, 100000000)
start = time.time()
chunks = (randomlist[i:i CHUNKSIZE]
for i in range(0, len(randomlist), CHUNKSIZE))
with mp.Pool(mp.cpu_count()) as pool:
local_maximum_list = pool.map(local_maximum, chunks)
print(f"Global maximum: {max(local_maximum_list)}")
end = time.time()
print(f"MP Elapsed time: {end-start:.2f}s")
表現
非常有趣的是隨機串列的創建如何影響多處理的性能
Scenario 1:
randomlist = np.random.randint(1, 30000000, 100000000)
MP Elapsed time: 1.63s
Scenario 2:
randomlist = np.random.randint(1, 30000000, 100000000).tolist()
MP Elapsed time: 6.02s
Scenario 3
randomlist = [random.randint(1, 30000000) for _ in range(100000000)]
MP Elapsed time: 7.14s
Scenario 4:
randomlist = list(np.random.randint(1, 30000000, 100000000))
MP Elapsed time: 184.28s
Scenario 5:
randomlist = []
for _ in range(100000000):
n = random.randint(1, 30000000)
randomlist.append(n)
MP Elapsed time: 7.52s
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359323.html
上一篇:Java同步帳戶示例未按預期作業
