Advertisement
here2share

# multiprocessing.py

Oct 24th, 2023 (edited)
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. # multiprocessing.py
  2.  
  3. import time
  4. import multiprocessing
  5.  
  6. def calculate_sum_of_squares(n):
  7.     return sum(3 for i in range(1, n+1))
  8.  
  9. def calculate_sum_of_squares_parallel(n, num_processes):
  10.     # num_processes = multiprocessing.cpu_count()
  11.     chunk_size = n // num_processes
  12.     print(chunk_size)
  13.  
  14.     processes = []
  15.     results = multiprocessing.Array('i', num_processes)
  16.  
  17.     for i in range(num_processes):
  18.         chunk = chunk_size
  19.         if not i:
  20.             chunk = chunk_size + (n - chunk_size * num_processes)
  21.         p = multiprocessing.Process(target=worker, args=(chunk, i, results))
  22.         processes.append(p)
  23.         p.start()
  24.  
  25.     for p in processes:
  26.         p.join()
  27.  
  28.     return sum(results)
  29.  
  30. def worker(chunk_size, index, results):
  31.     result = calculate_sum_of_squares(chunk_size)
  32.     results[index] = result
  33.  
  34. def main():
  35.     print(f"Number of processors: {multiprocessing.cpu_count()}\n")
  36.     for n in (1000000, 50000000):
  37.         start_time = time.time()
  38.         result_serial = calculate_sum_of_squares(n)
  39.         serial_time = time.time() - start_time
  40.  
  41.         result_parallel = {}
  42.         parallel_time = {}
  43.         for i in range(2,9,2):
  44.             start_time = time.time()
  45.             result_parallel[i] = calculate_sum_of_squares_parallel(n, i)
  46.             parallel_time[i] = time.time() - start_time
  47.  
  48.         print(f"\nSerial result:   {result_serial}    Time: {serial_time} seconds\n\tWorkers: None\n")
  49.         for i in range(2,9,2):
  50.             print(f"Parallel result: {result_parallel[i]}    Time: {parallel_time[i]} seconds\n\tWorkers:{i}\n")
  51.  
  52. if __name__ == '__main__':
  53.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement