3
# Author: Vitalii Vanovschi
4
# Desc: This program demonstrates parallel computations with pp module
5
# It calculates the sum of prime numbers below a given integer in parallel
6
# Parallel Python Software: http://www.parallelpython.com
14
"""Returns True if n is prime and False otherwise"""
15
if not isinstance(n, int):
16
raise TypeError("argument passed to is_prime is not of 'int' type")
21
max = int(math.ceil(math.sqrt(n)))
31
"""Calculates sum of all primes below given integer n"""
32
return len([sum([x for x in xrange(2, n) if isprime(x)]),sum([x for x in xrange(2, n) if isprime(x)])])
35
print """Usage: python sum_primes.py [ncpus]
36
[ncpus] - the number of workers to run in parallel,
37
if omitted it will be set to the number of processors in the system"""
39
# tuple of all parallel python servers to connect with
41
#ppservers = ("127.0.0.1:60000", )
44
ncpus = int(sys.argv[1])
45
# Creates jobserver with ncpus workers
46
job_server = pp.Server(ncpus, ppservers=ppservers)
48
# Creates jobserver with automatically detected number of workers
49
job_server = pp.Server(ppservers=ppservers)
51
print "Starting pp with", job_server.get_ncpus(), "workers"
53
# Submit a job of calulating sum_primes(100) for execution.
54
# sum_primes - the function
55
# (100,) - tuple with arguments for sum_primes
56
# (isprime,) - tuple with functions on which function sum_primes depends
57
# ("math",) - tuple with module names which must be imported before
58
# sum_primes execution
59
# Execution starts as soon as one of the workers will become available
60
job1 = job_server.submit(sum_primes, (100, ), (isprime, ), ("math", ))
62
# Retrieves the result calculated by job1
63
# The value of job1() is the same as sum_primes(100)
64
# If the job has not been finished yet, execution will
65
# wait here until result is available
68
print "Sum of primes below 100 is", result
71
# The following submits 8 jobs and then retrieves the results
72
inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700)
73
jobs = [(input, job_server.submit(sum_primes, (input, ), (isprime, ),
74
("math", ))) for input in inputs]
76
for input, job in jobs:
77
print "Sum of primes below", input, "is", job()
79
job_server.print_stats()
81
# Parallel Python Software: http://www.parallelpython.com