2023-12-04 23:02:40 +04:00
|
|
|
import multiprocessing
|
|
|
|
|
2023-12-04 21:25:59 +04:00
|
|
|
from flask import Flask, render_template, request
|
|
|
|
import numpy as np
|
|
|
|
import concurrent.futures
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def multiply_matrices(matrix_a, matrix_b):
|
2023-12-04 22:40:49 +04:00
|
|
|
if len(matrix_a[0]) != len(matrix_b):
|
2023-12-04 23:02:40 +04:00
|
|
|
raise ValueError("матрицы имеют разную длину")
|
2023-12-04 22:40:49 +04:00
|
|
|
|
|
|
|
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
|
|
|
|
|
2023-12-04 23:02:40 +04:00
|
|
|
|
|
|
|
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):
|
2023-12-04 22:40:49 +04:00
|
|
|
if len(matrix_a[0]) != len(matrix_b):
|
2023-12-04 23:02:40 +04:00
|
|
|
raise ValueError("матрицы имеют разную длину")
|
2023-12-04 22:40:49 +04:00
|
|
|
|
|
|
|
result = [[0 for _ in range(len(matrix_b[0]))] for _ in range(len(matrix_a))]
|
|
|
|
|
2023-12-04 23:02:40 +04:00
|
|
|
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)
|
2023-12-04 22:40:49 +04:00
|
|
|
|
2023-12-04 23:02:40 +04:00
|
|
|
for row_result, row_index in rows_results:
|
|
|
|
result[row_index] = row_result
|
2023-12-04 22:40:49 +04:00
|
|
|
|
2023-12-04 21:25:59 +04:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/')
|
|
|
|
def index():
|
|
|
|
return render_template('index.html')
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/multiply', methods=['POST'])
|
|
|
|
def multiply():
|
|
|
|
n = int(request.form.get('matrix_a'))
|
|
|
|
matrix_a = np.random.randint(10, size=(n, n))
|
|
|
|
matrix_b = np.random.randint(10, size=(n, n))
|
|
|
|
|
|
|
|
operation_type = request.form.get('operation_type')
|
|
|
|
|
|
|
|
if operation_type == 'sequential':
|
|
|
|
result = multiply_matrices(matrix_a, matrix_b)
|
|
|
|
elif operation_type == 'parallel':
|
2023-12-04 23:02:40 +04:00
|
|
|
result = multiply_matrices_parallel(matrix_a, matrix_b, 16)
|
2023-12-04 21:25:59 +04:00
|
|
|
else:
|
|
|
|
return "Invalid operation type"
|
|
|
|
|
|
|
|
return render_template('result.html', matrix_a=matrix_a, matrix_b=matrix_b, result=result)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run(debug=True)
|