Advertisement
ivapopova

GIL_effect.py

May 3rd, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. import multiprocessing as mp
  2. import time
  3.  
  4. def worker(r):
  5.     pid = mp.current_process().name
  6.  
  7.     # do some hard and time consuming work:
  8.     global result
  9.     res = 0
  10.  
  11.     for i in r:
  12.         res += i
  13.  
  14.     if "Process-" in pid:
  15.         output.put(result)
  16.     else:
  17.         result += res
  18.  
  19.  
  20.     print("Worker {} is working with {}".format(pid, r))
  21.  
  22.  
  23. if __name__ == '__main__':
  24.     #################################################
  25.     # Sequential Processing:
  26.     #################################################
  27.     t = time.time()
  28.     result = 0
  29.  
  30.     worker(range(50_000_000))
  31.     worker(range(50_000_000,100_000_000))
  32.  
  33.     print("Sequential Processing result: ", result)
  34.     print("Sequential Processing took:",time.time() - t,"\n")
  35.  
  36.     #################################################
  37.     # Multithreaded Processing:
  38.     #################################################
  39.     t = time.time()
  40.     # Define an output queue
  41.     output = mp.Queue()
  42.  
  43.     p1 = mp.Process(target=worker, args=(range(50_000_000),))
  44.     p2 = mp.Process(target=worker, args=(range(50_000_000,100_000_000),))
  45.  
  46.     p1.start();p2.start()
  47.     p1.join(); p2.join()
  48.  
  49.     print("Multiprocess Processing result: ", output.get())
  50.     print("Multiprocess Processing took:",time.time() - t,"\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement