primes.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from __future__ import with_statement
  2. import math
  3. import time
  4. import sys
  5. from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
  6. PRIMES = [
  7. 112272535095293,
  8. 112582705942171,
  9. 112272535095293,
  10. 115280095190773,
  11. 115797848077099,
  12. 117450548693743,
  13. 993960000099397]
  14. def is_prime(n):
  15. if n % 2 == 0:
  16. return False
  17. sqrt_n = int(math.floor(math.sqrt(n)))
  18. for i in range(3, sqrt_n + 1, 2):
  19. if n % i == 0:
  20. return False
  21. return True
  22. def sequential():
  23. return list(map(is_prime, PRIMES))
  24. def with_process_pool_executor():
  25. with ProcessPoolExecutor(10) as executor:
  26. return list(executor.map(is_prime, PRIMES))
  27. def with_thread_pool_executor():
  28. with ThreadPoolExecutor(10) as executor:
  29. return list(executor.map(is_prime, PRIMES))
  30. def main():
  31. for name, fn in [('sequential', sequential),
  32. ('processes', with_process_pool_executor),
  33. ('threads', with_thread_pool_executor)]:
  34. sys.stdout.write('%s: ' % name.ljust(12))
  35. start = time.time()
  36. if fn() != [True] * len(PRIMES):
  37. sys.stdout.write('failed\n')
  38. else:
  39. sys.stdout.write('%.2f seconds\n' % (time.time() - start))
  40. if __name__ == '__main__':
  41. main()