"""
The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously.
ProcessPoolExecutor uses the multiprocessing module
"""
from concurrent.futures import ProcessPoolExecutor
import math
import multiprocessing
import os
import sys
import time
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
109972689928541]
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
print('No of CPUs/Processors: {}' . format(multiprocessing.cpu_count()))
a = time.time()
#default max_workers is number of processors on the machine
with ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
b = time.time()
print('Time taken: {:.2f} secs'.format(b-a))
if __name__ == '__main__':
main()
Output:
No of CPUs/Processors: 4
112272535095293 is prime: True
112582705942171 is prime: True
112272535095293 is prime: True
115280095190773 is prime: True
115797848077099 is prime: True
109972689928541 is prime: False
Time taken: 12.67 secs
The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously.
ProcessPoolExecutor uses the multiprocessing module
"""
from concurrent.futures import ProcessPoolExecutor
import math
import multiprocessing
import os
import sys
import time
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
109972689928541]
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
print('No of CPUs/Processors: {}' . format(multiprocessing.cpu_count()))
a = time.time()
#default max_workers is number of processors on the machine
with ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
b = time.time()
print('Time taken: {:.2f} secs'.format(b-a))
if __name__ == '__main__':
main()
Output:
No of CPUs/Processors: 4
112272535095293 is prime: True
112582705942171 is prime: True
112272535095293 is prime: True
115280095190773 is prime: True
115797848077099 is prime: True
109972689928541 is prime: False
Time taken: 12.67 secs
No comments:
Post a Comment