Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from threading import Thread, active_count
- from multiprocessing import Process, Pool
- from math import cos
- import time
- P = 6
- def compute(n):
- t = time.time()
- for i in range(0,5*10**P):
- x = cos(i)
- # print("#"+str(n),time.time() - t)
- types = { "Multithreading": "thr",
- "Multiprocessing": "mp",
- "Sequential": "seq",
- "Pool imap_unordered": "pool1",
- "Pool apply_async": "pool2",
- "Pool map": "pool3",
- # "Pool (with, imap)": "pool4",
- }
- times = []
- for key in types:
- type = types[key]
- print(key)
- tt = time.time()
- if type == "thr":
- for i in range(0,10):
- thr = Thread(target=compute,args=(i,))
- thr.setDaemon(True)
- thr.start()
- elif type == "mp":
- prcs = []
- for i in range(0,10):
- pr = Process(target=compute,args=(i,))
- pr.start()
- prcs.append(pr)
- elif type == "seq":
- t = time.time()
- for i in range(0,10):
- compute(i)
- seq = True
- elif type == "pool1":
- p = Pool(processes=5)
- for i in range(0,10):
- p.imap_unordered(compute,(i,))
- elif type == "pool2":
- p = Pool(processes=5)
- for i in range(0,10):
- p.apply_async(compute,(i,))
- elif type == "pool3":
- p = Pool(processes=5)
- p.map(compute,range(10))
- elif type == "pool4":
- with Pool(processes=7) as p:
- for i in range(0,10):
- p.imap_unordered(compute,(i,))
- while True:
- if type == "seq" and seq == True:
- break
- if type == "thr" and active_count() == 1:
- break
- if type == "mp" and not any(map(Process.is_alive,prcs)):
- break
- if type[:4] == "pool" and int(type[4])<4:
- p.close()
- p.join()
- break
- times.append(key + " took "+str(time.time() - tt)+ " seconds to complete")
- for itm in times: print(itm)
Advertisement
Add Comment
Please, Sign In to add comment