here2share

# time_multiprocessing.py

May 10th, 2021
621
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # time_multiprocessing.py
  2.  
  3. import time
  4. from multiprocessing import Pool
  5.  
  6. def cpu_bound(number):
  7.     return sum(i * i for i in range(number))
  8.  
  9. def find_sums(numbers):
  10.     for number in numbers:
  11.         cpu_bound(number)
  12.  
  13. def find_sums_mp(numbers):
  14.     pool = Pool(processes=4)
  15.     pool.map(cpu_bound, numbers)
  16.     pool.terminate()
  17.  
  18. def find_sums_mp_8(numbers):
  19.     pool = Pool(processes=8)
  20.     pool.map(cpu_bound, numbers)
  21.     pool.terminate()
  22.  
  23. if __name__ == "__main__":
  24.     numbers = [1280*800*2 + x for x in range(20)]
  25.  
  26.     start_time = time.time()
  27.     find_sums(numbers)
  28.     duration = time.time() - start_time
  29.     print "Duration", duration, "seconds"
  30.  
  31.     start_time = time.time()
  32.     find_sums_mp(numbers)
  33.     duration = time.time() - start_time
  34.     print "Duration", duration, "seconds"
  35.  
  36.     start_time = time.time()
  37.     find_sums_mp_8(numbers)
  38.     duration = time.time() - start_time
  39.     print "Duration", duration, "seconds"
  40.  
RAW Paste Data