Guest User

Untitled

a guest
Dec 8th, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from threading import Thread, active_count
  2. from multiprocessing import Process, Pool
  3. from math import cos
  4. import time
  5.  
  6. P = 6
  7.  
  8. def compute(n):
  9.     t = time.time()
  10.     for i in range(0,5*10**P):
  11.         x = cos(i)
  12. #   print("#"+str(n),time.time() - t)
  13.  
  14. types = {   "Multithreading": "thr",
  15.             "Multiprocessing": "mp",
  16.             "Sequential": "seq",
  17.             "Pool imap_unordered": "pool1",
  18.             "Pool apply_async": "pool2",
  19.             "Pool map": "pool3",
  20. #           "Pool (with, imap)": "pool4",
  21.         }
  22. times = []
  23.  
  24.  
  25. for key in types:
  26.     type = types[key]
  27.     print(key)
  28.     tt = time.time()
  29.     if type == "thr":
  30.         for i in range(0,10):
  31.             thr = Thread(target=compute,args=(i,))
  32.             thr.setDaemon(True)
  33.             thr.start()
  34.     elif type == "mp":
  35.         prcs = []
  36.         for i in range(0,10):
  37.             pr = Process(target=compute,args=(i,))
  38.             pr.start()
  39.             prcs.append(pr)
  40.     elif type == "seq":
  41.         t = time.time()
  42.         for i in range(0,10):
  43.             compute(i)
  44.         seq = True
  45.     elif type == "pool1":
  46.         p = Pool(processes=5)
  47.         for i in range(0,10):
  48.             p.imap_unordered(compute,(i,))
  49.     elif type == "pool2":
  50.         p = Pool(processes=5)
  51.         for i in range(0,10):
  52.             p.apply_async(compute,(i,))
  53.     elif type == "pool3":
  54.         p = Pool(processes=5)
  55.         p.map(compute,range(10))
  56.     elif type == "pool4":
  57.         with Pool(processes=7) as p:
  58.             for i in range(0,10):
  59.                 p.imap_unordered(compute,(i,))
  60.  
  61.     while True:
  62.         if type == "seq" and seq == True:
  63.             break
  64.         if type == "thr" and active_count() == 1:
  65.             break
  66.         if type == "mp" and not any(map(Process.is_alive,prcs)):
  67.             break
  68.         if type[:4] == "pool" and int(type[4])<4:
  69.             p.close()
  70.             p.join()
  71.             break
  72.     times.append(key + " took "+str(time.time() - tt)+ " seconds to complete")
  73.  
  74. for itm in times: print(itm)
Advertisement
Add Comment
Please, Sign In to add comment