51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
|
import numpy as np
|
||
|
import time
|
||
|
import concurrent.futures
|
||
|
|
||
|
def calculate_determinant(matrix):
|
||
|
return np.linalg.det(matrix)
|
||
|
|
||
|
def calculate_determinant_parallel(matrix, num_threads):
|
||
|
result = 1.0
|
||
|
chunk_size = matrix.shape[0] // num_threads
|
||
|
|
||
|
def calculate_chunk(start, end):
|
||
|
nonlocal result
|
||
|
for i in range(start, end):
|
||
|
result *= matrix[i, i]
|
||
|
|
||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
|
||
|
futures = []
|
||
|
for i in range(0, matrix.shape[0], chunk_size):
|
||
|
futures.append(executor.submit(calculate_chunk, i, i + chunk_size))
|
||
|
|
||
|
for future in concurrent.futures.as_completed(futures):
|
||
|
future.result()
|
||
|
|
||
|
return result
|
||
|
|
||
|
def benchmark(matrix_size, num_threads_list=[1, 2, 4]):
|
||
|
# Генерация квадратной матрицы
|
||
|
matrix = np.random.rand(matrix_size, matrix_size)
|
||
|
|
||
|
# Бенчмарк для обычного нахождения детерминанта
|
||
|
start_time = time.time()
|
||
|
det_normal = calculate_determinant(matrix)
|
||
|
end_time = time.time()
|
||
|
print(f"Размер матрицы {matrix_size}x{matrix_size}")
|
||
|
print(f"Последовательный: Детерминант: {det_normal} Время выполнения: {end_time - start_time:.6f} секунд")
|
||
|
|
||
|
# Бенчмарк для параллельного нахождения детерминанта
|
||
|
for num_threads in num_threads_list:
|
||
|
start_time = time.time()
|
||
|
det_parallel = calculate_determinant_parallel(matrix, num_threads)
|
||
|
end_time = time.time()
|
||
|
print(f"Параллельный ({num_threads} поток): Детерминант: {det_parallel} Время выполнения: {end_time - start_time:.6f} секунд")
|
||
|
|
||
|
print()
|
||
|
|
||
|
# Запуск бенчмарков
|
||
|
benchmark(100)
|
||
|
benchmark(300)
|
||
|
benchmark(500)
|