在Python中,你可以使用多線程或多進程來實現函數的并行處理。這里有兩種方法:
concurrent.futures
庫中的ThreadPoolExecutor
實現多線程并行處理:import concurrent.futures
import time
def func(x):
print(f"Processing {x}")
time.sleep(1)
return x * x
data = [1, 2, 3, 4, 5]
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(func, data))
print("Results:", results)
concurrent.futures
庫中的ProcessPoolExecutor
實現多進程并行處理:import concurrent.futures
import time
def func(x):
print(f"Processing {x}")
time.sleep(1)
return x * x
data = [1, 2, 3, 4, 5]
with concurrent.futures.ProcessPoolExecutor() as executor:
results = list(executor.map(func, data))
print("Results:", results)
注意:多線程并行處理在I/O密集型任務中效果較好,而多進程并行處理在計算密集型任務中效果較好。在選擇并行處理方法時,請根據實際需求和任務類型進行選擇。