DAS_2024_1/davydov_yuriy_lab_5/main.py

60 lines
1.9 KiB
Python
Raw Normal View History

2024-12-20 12:58:37 +04:00
import random
import time
import multiprocessing
import numpy as np
# Генерация случайной матрицы
def create_random_matrix(dim):
return [[random.randint(0, 10) for _ in range(dim)] for _ in range(dim)]
# Умножение отдельной строки
def compute_row_product(row_idx, mat_a, mat_b, output_mat):
dim = len(mat_a)
for col_idx in range(dim):
for k in range(dim):
output_mat[row_idx][col_idx] += mat_a[row_idx][k] * mat_b[k][col_idx]
# Параллельное умножение матриц
def parallel_matrix_multiplication(mat_a, mat_b, num_workers):
dim = len(mat_a)
result_matrix = [[0] * dim for _ in range(dim)]
with multiprocessing.Pool(processes=num_workers) as pool:
pool.starmap(compute_row_product, [(i, mat_a, mat_b, result_matrix) for i in range(dim)])
return result_matrix
# Измерение времени выполнения
def run_benchmark(dim, num_workers=1):
mat_a = create_random_matrix(dim)
mat_b = create_random_matrix(dim)
start_time = time.time()
parallel_matrix_multiplication(mat_a, mat_b, num_workers)
elapsed_time = time.time() - start_time
return elapsed_time
def main():
# Размеры матриц
matrix_dimensions = [100, 300, 500]
# Количество рабочих процессов
worker_counts = [1, 2, 4, 6, 8]
# Печать таблицы с результатами
print("-*" * 40)
print(f"{'Количество процессов':<20}{'|100x100 (сек.)':<20}{'|300x300 (сек.)':<20}{'|500x500 (сек.)'}")
print("-*" * 40)
for workers in worker_counts:
row = f"{workers:<20}"
for dim in matrix_dimensions:
benchmark_time = run_benchmark(dim, workers)
row += f"|{benchmark_time:.4f}".ljust(20)
print(row)
print("-*" * 40)
if __name__ == "__main__":
main()