我定義了一個接受單個整數輸入并回傳輸出整數的函式。
def get_output(n):
output = # process the integer
return output
現在我已經定義了一個必須使用上面定義的函式進行處理的輸入串列。
input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]
現在我已經定義了一個空的輸出串列,它將存盤函式的輸出。
output_list = []
現在我想查看 的每一項input_list并將其附加到output_list. 我知道如何使用順序方式實作這一點,但我想知道如何并行化這個任務。提前致謝。
uj5u.com熱心網友回復:
IIUC你需要:
如果您的整數行程更受 IO 限制,執行緒可能會更好地作業。
執行緒的 IO 密集程度更高,因此,如果您需要這樣做,您可以嘗試:
from concurrent.futures import ThreadPoolExecutor
def get_output(n):
output = n ** 2
return output
input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]
output_list = []
if __name__ == '__main__':
with ThreadPoolExecutor(max_workers=6) as pool:
output_list.extend(pool.map(get_output, input_list))
print(output_list)
這會處理串列并對所有元素進行平方,它并行地將其應用于每 6 個元素,如您所見,我指定了max_workers=6.
如果您的整數行程更受 CPU 限制,請使用多處理。
使用幾乎相同的代碼:
from concurrent.futures import ProcessPoolExecutor
def get_output(n):
output = n ** 2
return output
input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]
output_list = []
if __name__ == '__main__':
with ProcessPoolExecutor(max_workers=6) as pool:
output_list.extend(pool.map(get_output, input_list))
print(output_list)
這樣做也是如此,它并行處理和平方每 6 個元素的所有元素。
兩個代碼輸出:
[1, 4, 9, 25, 36, 64, 25, 25, 64, 36, 25, 4, 25, 4, 25, 16, 25, 4]
uj5u.com熱心網友回復:
首先將輸出附加到“input_list”中。
output_list = numpy.zeros_like(input_list)
output_list = input_list
陣列編程在這里發生。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318760.html
