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