Advertisement
ivapopova

GIL_effect.py

May 3rd, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. import threading
  2. import time
  3.  
  4. def worker(r):
  5. tid = threading.currentThread().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. result += res
  15. print("Worker {} is working with {}".format(tid, r))
  16.  
  17.  
  18. #################################################
  19. # Sequential Processing:
  20. #################################################
  21. t = time.time()
  22. result = 0
  23.  
  24. worker(range(500_000))
  25. worker(range(500_000,1_000_000))
  26.  
  27. print("Sequential Processing result: ", result)
  28. print("Sequential Processing took:",time.time() - t,"\n")
  29.  
  30. #################################################
  31. # Multithreaded Processing:
  32. #################################################
  33. t = time.time()
  34. result = 0
  35.  
  36. tr1 = threading.Thread(target=worker, args=(range(50_000_00),))
  37. tr2 = threading.Thread(target=worker, args=(range(50_000_00,100_000_00),))
  38.  
  39. tr1.start();tr2.start()
  40. tr1.join(); tr2.join()
  41.  
  42. print("Multithreaded Processing result: ", result)
  43. print("Multithreaded Processing took:",time.time() - t,"\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement