Parallel Python 並行開發多核心並行程式(例3)

來源:互聯網
上載者:User
#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name:        # Purpose:     ## Author:      ankier## Created:     05-02-2013# Copyright:   (c) ankier 2013# Licence:     <your licence>#-------------------------------------------------------------------------------import math, sys, md5, timeimport ppdef part_sum(start, end):    """Calculates partial sum"""    sum = 0    for x in xrange(start, end):        if x % 2 == 0:           sum -= 1.0 / x         else:           sum += 1.0 / x     return sumstart = 1end = 20000000# Divide the task into 64 subtasksparts = 64step = (end - start) / parts + 1# Create jobserverjob_server = pp.Server()# Execute the same task with different amount of active workers and measure the timefor ncpus in (1, 2, 4, 8, 16, 1):    job_server.set_ncpus(ncpus)    jobs = []    start_time = time.time()    print "Starting ", job_server.get_ncpus(), " workers"    for index in xrange(parts):        starti = start+index*step        endi = min(start+(index+1)*step, end)        jobs.append(job_server.submit(part_sum, (starti, endi)))       # Retrieve all the results and calculate their sum    part_sum1 = sum([job() for job in jobs])    # Print the partial sum    print "Partial sum is", part_sum1, "| diff =", math.log(2) - part_sum1    print "Time elapsed: ", time.time() - start_time, "s"    printjob_server.print_stats()

運行結果:

Starting  1  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  3.40600013733 sStarting  2  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  2.04699993134 sStarting  4  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  1.6740000248 sStarting  8  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  1.66700005531 sStarting  16  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  1.67000007629 sStarting  1  workersPartial sum is 0.69314720556 | diff = -2.50000427027e-08Time elapsed:  3.36299991608 sJob execution statistics: job count | % of all jobs | job time sum | time per job | job server       384 |        100.00 |      29.3340 |     0.076391 | localTime elapsed since server creation 15.20600008960 active tasks, 1 cores

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.