DAS_2024_1/ismailov_rovshan_lab_5/main.py

60 lines
1.9 KiB
Python
Raw Normal View History

2024-12-15 06:47:19 +04:00
import random
import time
import multiprocessing
import numpy as np
def create_random_matrix(size):
return [[random.randint(0, 10) for _ in range(size)] for _ in range(size)]
# Функция для умножения одной строки матрицы
def process_row(i, A, B, result):
size = len(A)
for j in range(size):
for k in range(size):
result[i][j] += A[i][k] * B[k][j]
# Функция для параллельного умножения матриц с использованием multiprocessing
def multiply_matrices_in_parallel(A, B, num_processes):
size = len(A)
result = [[0] * size for _ in range(size)]
with multiprocessing.Pool(processes=num_processes) as pool:
pool.starmap(process_row, [(i, A, B, result) for i in range(size)])
return result
# Функция для измерения времени выполнения умножения матриц
def measure_execution_time(size, num_processes=1):
A = create_random_matrix(size)
B = create_random_matrix(size)
start_time = time.time()
multiply_matrices_in_parallel(A, B, num_processes)
elapsed_time = time.time() - start_time
return elapsed_time
def main():
matrix_sizes = [100, 300, 500]
process_count_options = [1, 2, 4, 6, 8]
print("-*" * 40)
print(f"{'Количество потоков':<20}{'|100x100 (сек.)':<20}{'|300x300 (сек.)':<20}{'|500x500 (сек.)'}")
print("-*" * 40)
# Запуск тестов для разных значений числа процессов
for num_processes in process_count_options:
row = f"{num_processes:<20}"
for size in matrix_sizes:
par_time = measure_execution_time(size, num_processes)
row += f"|{par_time:.4f}".ljust(20)
print(row)
print("-*" * 40)
if __name__ == "__main__":
main()