example22.py 1011 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. 多进程和进程池的使用
  3. 多线程因为GIL的存在不能够发挥CPU的多核特性
  4. 对于计算密集型任务应该考虑使用多进程
  5. time python3 example22.py
  6. real 0m11.512s
  7. user 0m39.319s
  8. sys 0m0.169s
  9. """
  10. import concurrent.futures
  11. import math
  12. PRIMES = [
  13. 1116281,
  14. 1297337,
  15. 104395303,
  16. 472882027,
  17. 533000389,
  18. 817504243,
  19. 982451653,
  20. 112272535095293,
  21. 112582705942171,
  22. 112272535095293,
  23. 115280095190773,
  24. 115797848077099,
  25. 1099726899285419
  26. ] * 5
  27. def is_prime(n):
  28. """判断素数"""
  29. if n % 2 == 0:
  30. return False
  31. sqrt_n = int(math.floor(math.sqrt(n)))
  32. for i in range(3, sqrt_n + 1, 2):
  33. if n % i == 0:
  34. return False
  35. return True
  36. def main():
  37. """主函数"""
  38. with concurrent.futures.ProcessPoolExecutor() as executor:
  39. for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
  40. print('%d is prime: %s' % (number, prime))
  41. if __name__ == '__main__':
  42. main()