49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
|
import numpy as np
|
||
|
import time
|
||
|
import concurrent.futures
|
||
|
|
||
|
def multiply_matrices(matrix1, matrix2):
|
||
|
return np.dot(matrix1, matrix2)
|
||
|
|
||
|
def multiply_matrices_parallel(matrix1, matrix2, num_threads):
|
||
|
result = np.zeros_like(matrix1)
|
||
|
chunk_size = matrix1.shape[0] // num_threads
|
||
|
|
||
|
def multiply_chunk(start, end):
|
||
|
nonlocal result
|
||
|
for i in range(start, end):
|
||
|
result[i] = np.dot(matrix1[i], matrix2)
|
||
|
|
||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
|
||
|
futures = []
|
||
|
for i in range(0, matrix1.shape[0], chunk_size):
|
||
|
futures.append(executor.submit(multiply_chunk, i, i + chunk_size))
|
||
|
|
||
|
for future in concurrent.futures.as_completed(futures):
|
||
|
future.result()
|
||
|
|
||
|
return result
|
||
|
|
||
|
def benchmark(matrix_size, num_threads=1):
|
||
|
# Генерация матриц
|
||
|
matrix1 = np.random.rand(matrix_size, matrix_size)
|
||
|
matrix2 = np.random.rand(matrix_size, matrix_size)
|
||
|
|
||
|
# Бенчмарк для обычного умножения
|
||
|
start_time = time.time()
|
||
|
result = multiply_matrices(matrix1, matrix2)
|
||
|
end_time = time.time()
|
||
|
print(f"Размер матрицы {matrix_size}x{matrix_size}")
|
||
|
print(f"Время при обычном выполнении: {end_time - start_time} секунд")
|
||
|
|
||
|
# Бенчмарк для параллельного умножения
|
||
|
start_time = time.time()
|
||
|
result_parallel = multiply_matrices_parallel(matrix1, matrix2, num_threads)
|
||
|
end_time = time.time()
|
||
|
print(f"Время при параллельном выполнении ({num_threads} потоков): {end_time - start_time} секунд\n")
|
||
|
|
||
|
# Запуск бенчмарков
|
||
|
benchmark(100)
|
||
|
benchmark(300)
|
||
|
benchmark(500)
|