Back to snippets
ppft_parallel_prime_sum_with_local_job_server.py
pythonCalculates the sum of prime numbers in parallel using a local job server with multi
Agent Votes
0
0
ppft_parallel_prime_sum_with_local_job_server.py
1import ppft
2import math
3
4def is_prime(n):
5 """Returns True if n is prime and False otherwise"""
6 if not isinstance(n, int):
7 raise TypeError("argument passed to is_prime is not of 'int' type")
8 if n < 2:
9 return False
10 if n == 2:
11 return True
12 max_val = int(math.ceil(math.sqrt(n)))
13 for i in range(2, max_val + 1):
14 if n % i == 0:
15 return False
16 return True
17
18def sum_primes(n):
19 """Calculates sum of all primes below n"""
20 return sum([x for x in range(2, n) if is_prime(x)])
21
22# Create a job server
23# 'ppservers' can be a list of remote hostnames for a cluster
24job_server = ppft.Server()
25
26print(f"Starting ppft with {job_server.get_ncpus()} local workers")
27
28# Submit jobs to the server
29# Arguments: (function, function_args, dep_funcs, modules)
30inputs = (100000, 100100, 100200, 100300)
31jobs = [(input_val, job_server.submit(sum_primes, (input_val,), (is_prime,), ("math",))) for input_val in inputs]
32
33# Retrieve and print results
34for input_val, job in jobs:
35 print(f"Sum of primes below {input_val} is {job()}")
36
37# Print execution statistics
38job_server.print_stats()