DAS_2024_1/davydov_yuriy_lab_5/main.py
2024-12-20 11:58:37 +03:00

60 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()