自建进程池
# 示例19-12 sequential.py:对一个小型数据集做指数检测(顺序执行版)
"""
sequential.py: CPU密集型工作的舒徐执行版,多线程版和多进程版的比较基准
"""
from time import perf_counter
from typing import NamedTuple
from primes import is_prime, NUMBERS
class Result(NamedTuple): # 1
prime: bool
elapsed: float
def check(n: int) -> Result: # 2
t0 = perf_counter()
prime = is_prime(n)
return Result(prime, perf_counter() - t0)
def main() -> None:
print(f'Checking {len(NUMBERS)} numbers sequentially:')
t0 = perf_counter()
for n in NUMBERS: # 3
prime, elapsed = check(n)
label = 'P' if prime else ' '
print(f'{n:16} {label} {elapsed:9.6f}s')
elapsed = perf_counter() - t0 # 4
print(f'Total time:{elapsed:.2f}s')
if __name__ == '__main__':
main()
- check函数 返回一个Result 元组,包含is_prime 调用返回的布尔值和用时
- check(n) 调用 is_prime(n),并计算用时,返回一个Result
- 调用check检查样本中的每个数,显示结果。
- 计算并显示总用时。