5 лаба без ридми
This commit is contained in:
parent
bc087de470
commit
f4db3f2d43
57
karamushko_maxim_lab_5/main.py
Normal file
57
karamushko_maxim_lab_5/main.py
Normal file
@ -0,0 +1,57 @@
|
||||
import random
|
||||
import time
|
||||
import multiprocessing
|
||||
|
||||
# Генерация матрицы
|
||||
def matrix_generate(size):
|
||||
return [[random.randint(0, 50) for _ in range(size)] for _ in range(size)]
|
||||
|
||||
# Умножение строк
|
||||
def row_multi(i, A, B, result):
|
||||
size = len(A)
|
||||
for j in range(size):
|
||||
for k in range(size):
|
||||
result[i][j] += A[i][k] * B[k][j]
|
||||
|
||||
# параллельное умножение с помощью multiprocessing
|
||||
def matrix_mulit_parallel(A, B, num_processes):
|
||||
size = len(A)
|
||||
result = [[0] * size for _ in range(size)]
|
||||
|
||||
with multiprocessing.Pool(processes=num_processes) as pool:
|
||||
pool.starmap(row_multi, [(i, A, B, result) for i in range(size)])
|
||||
|
||||
return result
|
||||
|
||||
# Замер времени
|
||||
def measure_time(size, num_processes=1):
|
||||
A = matrix_generate(size)
|
||||
B = matrix_generate(size)
|
||||
|
||||
start_time = time.time()
|
||||
matrix_mulit_parallel(A, B, num_processes)
|
||||
par_time = time.time() - start_time
|
||||
|
||||
return par_time
|
||||
|
||||
def main():
|
||||
# Размеры матриц
|
||||
matrix_sizes = [100, 300, 500]
|
||||
# Количество потоков
|
||||
num_processes_list = [1, 2, 4, 6, 8]
|
||||
# Таблица с замерами времени
|
||||
print("-*" * 40)
|
||||
print(f"{'Количество потоков':<20}{'|100x100 (сек.)':<20}{'|300x300 (сек.)':<20}{'|500x500 (сек.)'}")
|
||||
print("-*" * 40)
|
||||
|
||||
for num_processes in num_processes_list:
|
||||
row = f"{num_processes:<20}"
|
||||
|
||||
for size in matrix_sizes:
|
||||
par_time = measure_time(size, num_processes)
|
||||
row += f"|{par_time:.4f}".ljust(20)
|
||||
print(row)
|
||||
print("-*" * 40)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Loading…
Reference in New Issue
Block a user