74 lines
2.5 KiB
Python
74 lines
2.5 KiB
Python
|
import numpy as np
|
||
|
import time
|
||
|
import multiprocessing
|
||
|
import concurrent.futures
|
||
|
|
||
|
|
||
|
def multiply_matrices_sequential(matrix_a, matrix_b):
|
||
|
if len(matrix_a[0]) != len(matrix_b):
|
||
|
raise ValueError("матрицы имеют разную длину")
|
||
|
|
||
|
result = [[0 for _ in range(len(matrix_b[0]))] for _ in range(len(matrix_a))]
|
||
|
|
||
|
for i in range(len(matrix_a)):
|
||
|
for j in range(len(matrix_b[0])):
|
||
|
for k in range(len(matrix_b)):
|
||
|
result[i][j] += matrix_a[i][k] * matrix_b[k][j]
|
||
|
|
||
|
return result
|
||
|
|
||
|
|
||
|
def multiply_row(args):
|
||
|
matrix_a, matrix_b, i = args
|
||
|
row_result = [0 for _ in range(len(matrix_b[0]))]
|
||
|
for j in range(len(matrix_b[0])):
|
||
|
for k in range(len(matrix_b)):
|
||
|
row_result[j] += matrix_a[i][k] * matrix_b[k][j]
|
||
|
return row_result, i
|
||
|
|
||
|
|
||
|
def multiply_matrices_parallel(matrix_a, matrix_b, threads):
|
||
|
if len(matrix_a[0]) != len(matrix_b):
|
||
|
raise ValueError("матрицы имеют разную длину")
|
||
|
|
||
|
result = [[0 for _ in range(len(matrix_b[0]))] for _ in range(len(matrix_a))]
|
||
|
|
||
|
with multiprocessing.Pool(processes=threads) as pool:
|
||
|
args_list = [(matrix_a, matrix_b, i) for i in range(len(matrix_a))]
|
||
|
rows_results = pool.map(multiply_row, args_list)
|
||
|
|
||
|
for row_result, row_index in rows_results:
|
||
|
result[row_index] = row_result
|
||
|
|
||
|
return result
|
||
|
|
||
|
|
||
|
# Бенчмарк тесты
|
||
|
def benchmark(matrix_size, num_threads):
|
||
|
A = np.random.rand(matrix_size, matrix_size)
|
||
|
B = np.random.rand(matrix_size, matrix_size)
|
||
|
|
||
|
# Последовательное умножение
|
||
|
start_time = time.time()
|
||
|
multiply_matrices_sequential(A, B)
|
||
|
sequential_time = time.time() - start_time
|
||
|
|
||
|
# Параллельное умножение
|
||
|
start_time = time.time()
|
||
|
multiply_matrices_parallel(A, B, num_threads)
|
||
|
parallel_time = time.time() - start_time
|
||
|
|
||
|
print(f"Размер матрицы: {matrix_size}x{matrix_size}")
|
||
|
print(f"Время последовательного алгоритма: {sequential_time:.4f} секунд")
|
||
|
print(f"Время параллельного алгоритма ({num_threads} потоков): {parallel_time:.4f} секунд")
|
||
|
print("\n")
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
|
||
|
# Проведение бенчмарков
|
||
|
sizes = [100, 300, 500]
|
||
|
for size in sizes:
|
||
|
benchmark(size, num_threads=1) # 1 поток для проверки равенства результатов
|
||
|
benchmark(size, num_threads=4) # 4 потока
|