Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # multiprocessing.py
- import time
- import multiprocessing
- def calculate_sum_of_squares(n):
- return sum(3 for i in range(1, n+1))
- def calculate_sum_of_squares_parallel(n, num_processes):
- # num_processes = multiprocessing.cpu_count()
- chunk_size = n // num_processes
- print(chunk_size)
- processes = []
- results = multiprocessing.Array('i', num_processes)
- for i in range(num_processes):
- chunk = chunk_size
- if not i:
- chunk = chunk_size + (n - chunk_size * num_processes)
- p = multiprocessing.Process(target=worker, args=(chunk, i, results))
- processes.append(p)
- p.start()
- for p in processes:
- p.join()
- return sum(results)
- def worker(chunk_size, index, results):
- result = calculate_sum_of_squares(chunk_size)
- results[index] = result
- def main():
- print(f"Number of processors: {multiprocessing.cpu_count()}\n")
- for n in (1000000, 50000000):
- start_time = time.time()
- result_serial = calculate_sum_of_squares(n)
- serial_time = time.time() - start_time
- result_parallel = {}
- parallel_time = {}
- for i in range(2,9,2):
- start_time = time.time()
- result_parallel[i] = calculate_sum_of_squares_parallel(n, i)
- parallel_time[i] = time.time() - start_time
- print(f"\nSerial result: {result_serial} Time: {serial_time} seconds\n\tWorkers: None\n")
- for i in range(2,9,2):
- print(f"Parallel result: {result_parallel[i]} Time: {parallel_time[i]} seconds\n\tWorkers:{i}\n")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement