python並行計算的簡單實現--pp

來源:互聯網
上載者:User

標籤:python   並行計算   pp   多線程   編程   

python多線程最出名的是 mutilprocessing (mp) 然而我推薦一個第三方的包, 它的實現比mp 簡單地多, 只需要一句話

job = job_server.submit(function, (paras,), (called-functions,), (imports,))

非常容易理解,
1. function是你需要並行計算的函數,
2. paras是實參,
3. called-functions 是function中調用的其他函數, 如果沒有, 則不填.
4. imports 是這個function中調用的庫

下面我示範一個並行計算n以內所有質數加和,

1. 建立伺服器
ppservers = ()job_server = pp.Server(ppservers=ppservers)

這裡, 你的電腦有幾個CPU, 它就會建立幾台伺服器
通過下面代碼可以擷取CPU個數:

job_server.get_ncpus()#8

比如我的是8個

2. 構造需要並行計算的函數
def isprime(n):    """Returns True if n is prime and False otherwise"""    if not isinstance(n, int):        raise TypeError("argument passed to is_prime is not of ‘int‘ type")    if n < 2:        return False    if n == 2:        return True    max = int(math.ceil(math.sqrt(n)))    i = 2    while i <= max:        if n % i == 0:            return False        i += 1    return Truedef sum_primes(n):    """Calculates sum of all primes below given integer n"""    return sum([x for x in xrange(2,n) if isprime(x)])
3. 提交任務給伺服器進行計算
import ppinputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700,100800)jobs = [(input, job_server.submit(sum_primes,(input,), (isprime,), ("math",))) for input in inputs]for input, job in jobs:    print "Sum of primes below", input, "is", job()
結束語

如果你想比較並行計算和正常python的效率, 有兩個辦法可以實現

1. python time庫
 import sys, time start_time = time.time()print "Time elapsed: ", time.time() - start_time, "s"
2. pp內建效率統計函數
job_server.print_stats()

好了, 現在用pp讓你的python飛起吧~

python並行計算的簡單實現--pp

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.