Код: Выделить всё
from multiprocessing import Process
import time
import random
def calculate_squares(numbers):
for num in numbers:
square = num * num
if __name__ == "__main__":
numbers = [random.randrange(1, 50, 1) for i in range(100000000)]
quarter = len(numbers) // 4
first_part = numbers[:quarter]
second_part = numbers[quarter:2*quarter]
third_part = numbers[2*quarter:3*quarter]
fourth_part = numbers[3*quarter:]
start_time = time.time()
# Creating four processes
p1 = Process(target=calculate_squares, args=(first_part,))
p2 = Process(target=calculate_squares, args=(second_part,))
p3 = Process(target=calculate_squares, args=(third_part,))
p4 = Process(target=calculate_squares, args=(fourth_part,))
# Start all processes
p1.start()
p2.start()
p3.start()
p4.start()
# Wait for all processes to complete
p1.join()
p2.join()
p3.join()
p4.join()
end_time = time.time()
print(f"Execution time with four processes: {(end_time - start_time) * 10**3} ms")
# Single process execution for comparison
start_time = time.time()
calculate_squares(numbers)
end_time = time.time()
print(f"Execution time for single process: {(end_time - start_time) * 10**3} ms")
вывод для i5 13gen (windows):
Время выполнения с четырьмя процессы: 4975,9681224823 мс
Время выполнения одного процесса: 3258,450984954834 мс
выход для i3 8gen (linux):
Время выполнения четырех процессов: 1378,4070014953613 мс
Время выполнения одного процесса: 2259,6046924591064 ms
выход для Mac m1:
Время выполнения четырех процессов: 3175,5270957946777 мс
Время выполнения одного процесса: 2120,435953140259 мс
Подробнее здесь: https://stackoverflow.com/questions/791 ... -processor