#-*- 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