Code works.
Here with added timing and
max_workers=8
(use 8 cores).
Then it should be easier to see if it work,and
run from command line
not any editors when this out.
import concurrent.futures
import math, time
PRIMES = [
111111111191122,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419
] * 10 # Longer run time
def is_prime(n):
if n < 2:
return False
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():
start = time.time()
with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print(f'{number} is prime: {prime}')
stop = time.time()
total = stop - start
print(f'Time was: {total:.2f}')
if __name__ == '__main__':
main()
Output:
.....
115280095190773 is prime: True
115797848077099 is prime: True
1099726899285419 is prime: False
Time was: 6.17
If set
max_workers=1
also now use only 1 core in CPU.
The time should be slower.
Output:
.....
115280095190773 is prime: True
115797848077099 is prime: True
1099726899285419 is prime: False
Time was: 23.63