DAS_2024_1/klyushenkova_ksenia_lab_6/main-1.py

65 lines
2.0 KiB
Python
Raw Normal View History

2024-12-20 22:02:59 +04:00
import numpy as np
from time import time
import multiprocessing
def task(matrix, start_j, stop_j, queue):
size = len(matrix[0])
if size == 2: # Базовый случай: определитель 2x2
det = matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]
if queue is not None:
queue.put(det)
return det
else:
res = 0
for j in range(start_j, stop_j):
# Удаляем строку и столбец с помощью срезов (более эффективно)
tmp = matrix[1:, :j]
tmp = np.hstack((tmp, matrix[1:, j + 1:]))
a = matrix[0][j]
b = task(tmp, 0, len(tmp[0]), None)
if j % 2 == 0:
res += a * b
else:
res += a * b * (-1)
if queue is not None:
queue.put(res)
return res
if __name__ == '__main__':
sizes = [5, 6, 7, 8, 9, 10]
threads_counts = [1, 4, 6, 8, 10]
for threads in threads_counts:
print(f'Количество потоков: {threads}')
for size in sizes:
matrix = np.random.randint(10, size=(size, size))
offset = int(size / threads)
offset_last = size % threads + offset
processes = []
queue = multiprocessing.Queue()
start = time()
for i in range(threads):
start_ = i * offset
stop_ = start_ + offset_last if i == threads - 1 else start_ + offset
process = multiprocessing.Process(target=task, args=(matrix, start_, stop_, queue))
processes.append(process)
process.start()
total_result = 0
for p in processes:
p.join()
total_result += queue.get()
stop = time()
print(f'Размер: {size}x{size}, время выполнения: {stop - start} сек')
print()