[英]Parallelism in Python
在Python中實現並行性有哪些選擇? 我想對一些非常大的柵格執行一堆CPU綁定計算,並希望將它們並行化。 來自C背景,我熟悉三種並行方法:
決定使用方法是權衡利弊。
在Python中,有哪些方法可用,它們的特征是什么? 是否有可群集的MPI克隆? 實現共享內存並行性的首選方法是什么? 我聽說過GIL的問題,以及對tasklet的引用。
簡而言之,在選擇它們之前,我需要了解Python中的不同並行化策略?
新的(2.6) 多處理模塊是要走的路。 它使用子進程來解決GIL問題。 它還抽象出一些本地/遠程問題,因此可以在以后選擇在本地運行代碼或在群集上分布。 我上面鏈接的文檔有點可以咀嚼,但應該提供一個良好的入門基礎。
Ray是一個優雅(快速)的庫。
並行化Python函數的最基本策略是使用@ray.remote
裝飾器聲明一個函數。 然后可以異步調用它。
import ray
import time
# Start the Ray processes (e.g., a scheduler and shared-memory object store).
ray.init(num_cpus=8)
@ray.remote
def f():
time.sleep(1)
# This should take one second assuming you have at least 4 cores.
ray.get([f.remote() for _ in range(4)])
您還可以使用@ray.remote
裝飾器,使用actor並行化有狀態計算。
# This assumes you already ran 'import ray' and 'ray.init()'.
import time
@ray.remote
class Counter(object):
def __init__(self):
self.x = 0
def inc(self):
self.x += 1
def get_counter(self):
return self.x
# Create two actors which will operate in parallel.
counter1 = Counter.remote()
counter2 = Counter.remote()
@ray.remote
def update_counters(counter1, counter2):
for _ in range(1000):
time.sleep(0.25)
counter1.inc.remote()
counter2.inc.remote()
# Start three tasks that update the counters in the background also in parallel.
update_counters.remote(counter1, counter2)
update_counters.remote(counter1, counter2)
update_counters.remote(counter1, counter2)
# Check the counter values.
for _ in range(5):
counter1_val = ray.get(counter1.get_counter.remote())
counter2_val = ray.get(counter2.get_counter.remote())
print("Counter1: {}, Counter2: {}".format(counter1_val, counter2_val))
time.sleep(1)
與多處理模塊相比,它具有許多優點:
Ray是我一直在幫助開發的框架。
根據您需要處理多少數據以及您打算使用多少CPU /機器,在某些情況下,使用C(或Java / C#,如果您想使用jython / IronPython)編寫部分數據更好
您可以從中獲得的加速比在8個CPU上並行運行更能提高性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.