ch21 examples

This commit is contained in:
Luciano Ramalho
2021-02-12 22:53:10 -03:00
parent 93bb4407fa
commit ace44eeaf2
16 changed files with 854 additions and 0 deletions

52
21-futures/primes/primes.py Executable file
View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
import math
PRIME_FIXTURE = [
(2, True),
(142702110479723, True),
(299593572317531, True),
(3333333333333301, True),
(3333333333333333, False),
(3333335652092209, False),
(4444444444444423, True),
(4444444444444444, False),
(4444444488888889, False),
(5555553133149889, False),
(5555555555555503, True),
(5555555555555555, False),
(6666666666666666, False),
(6666666666666719, True),
(6666667141414921, False),
(7777777536340681, False),
(7777777777777753, True),
(7777777777777777, False),
(9999999999999917, True),
(9999999999999999, False),
]
NUMBERS = [n for n, _ in PRIME_FIXTURE]
# tag::IS_PRIME[]
def is_prime(n: int) -> bool:
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
root = math.isqrt(n)
for i in range(3, root + 1, 2):
if n % i == 0:
return False
return True
# end::IS_PRIME[]
if __name__ == '__main__':
for n, prime in PRIME_FIXTURE:
prime_res = is_prime(n)
assert prime_res == prime
print(n, prime)

50
21-futures/primes/proc_pool.py Executable file
View File

@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""
proc_pool.py: a version of the proc.py example from chapter 20,
but using `concurrent.futures.ProcessPoolExecutor`.
"""
# tag::PRIMES_POOL[]
from time import perf_counter
from typing import NamedTuple
from concurrent import futures # <1>
import sys
from primes import is_prime, NUMBERS
class PrimeResult(NamedTuple): # <2>
n: int
flag: bool
elapsed: float
def check(n: int) -> PrimeResult:
t0 = perf_counter()
res = is_prime(n)
return PrimeResult(n, res, perf_counter() - t0)
def main() -> None:
if len(sys.argv) < 2:
workers = None # <3>
else:
workers = int(sys.argv[1])
executor = futures.ProcessPoolExecutor(workers) # <4>
actual_workers = executor._max_workers # type: ignore # <5>
print(f'Checking {len(NUMBERS)} numbers with {actual_workers} processes:')
t0 = perf_counter()
numbers = sorted(NUMBERS, reverse=True) # <6>
with executor: # <7>
for n, prime, elapsed in executor.map(check, numbers): # <8>
label = 'P' if prime else ' '
print(f'{n:16} {label} {elapsed:9.6f}s')
time = perf_counter() - t0
print('Total time:', f'{time:0.2f}s')
if __name__ == '__main__':
main()
# end::PRIMES_POOL[]