簡體   English   中英

Python中的並行性

[英]Parallelism in Python

在Python中實現並行性有哪些選擇? 我想對一些非常大的柵格執行一堆CPU綁定計算,並希望將它們並行化。 來自C背景,我熟悉三種並行方法:

  1. 消息傳遞過程,可能分布在集群中,例如MPI
  2. 顯式共享內存並行,使用pthreadsfork()pipe()等。
  3. 隱式共享內存並行,使用OpenMP

決定使用方法是權衡利弊。

在Python中,有哪些方法可用,它們的特征是什么? 是否有可群集的MPI克隆? 實現共享內存並行性的首選方法是什么? 我聽說過GIL的問題,以及對tasklet的引用。

簡而言之,在選擇它們之前,我需要了解Python中的不同並行化策略?

通常,您描述CPU綁定計算。 這不是Python的強項。 從歷史上看,它們都不是多處理的。

主流Python解釋器中的線程已被可怕的全局鎖定所統治。 新的多處理 API可以解決這個問題,並通過管道和隊列等提供工作池抽象。

您可以用CCython編寫性能關鍵代碼,並使用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是我一直在幫助開發的框架。

有許多軟件包可以做到這一點,其中最合適的是多處理,特別是“Pool”類。

通過並行python可以獲得類似的結果,此外,它還可以與集群一起使用。

無論如何,我會說多處理。

根據您需要處理多少數據以及您打算使用多少CPU /機器,在某些情況下,使用C(或Java / C#,如果您想使用jython / IronPython)編寫部分數據更好

您可以從中獲得的加速比在8個CPU上並行運行更能提高性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM