|
| 1 | +# tag::PRIMES_PROC_TOP[] |
| 2 | +from time import perf_counter |
| 3 | +from typing import Tuple, List, NamedTuple |
| 4 | +from multiprocessing import Process, SimpleQueue # <1> |
| 5 | + |
| 6 | +from primes import is_prime, NUMBERS |
| 7 | + |
| 8 | +class Result(NamedTuple): # <3> |
| 9 | + flag: bool |
| 10 | + elapsed: float |
| 11 | + |
| 12 | +def check(n: int) -> Result: # <5> |
| 13 | + t0 = perf_counter() |
| 14 | + res = is_prime(n) |
| 15 | + return Result(res, perf_counter() - t0) |
| 16 | + |
| 17 | +def job(n: int, results) -> None: # <6> |
| 18 | + results.put((n, check(n))) # <7> |
| 19 | +# end::PRIMES_PROC_TOP[] |
| 20 | + |
| 21 | +# tag::PRIMES_PROC_MAIN[] |
| 22 | +def main() -> None: |
| 23 | + t0 = perf_counter() |
| 24 | + results = SimpleQueue() # <1> |
| 25 | + workers: List[Process] = [] # <2> |
| 26 | + |
| 27 | + for n in NUMBERS: |
| 28 | + worker = Process(target=job, args=(n, results)) # <3> |
| 29 | + worker.start() # <4> |
| 30 | + workers.append(worker) # <5> |
| 31 | + |
| 32 | + for _ in workers: # <6> |
| 33 | + n, (prime, elapsed) = results.get() # <7> |
| 34 | + label = 'P' if prime else ' ' |
| 35 | + print(f'{n:16} {label} {elapsed:9.6f}s') |
| 36 | + |
| 37 | + |
| 38 | + time = perf_counter() - t0 |
| 39 | + print('Total time:', f'{time:0.2f}s') |
| 40 | + |
| 41 | +if __name__ == '__main__': |
| 42 | + main() |
| 43 | +# end::PRIMES_PROC_MAIN[] |
0 commit comments