73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
import multiprocessing
|
|
|
|
from flask import Flask, render_template, request
|
|
import numpy as np
|
|
import concurrent.futures
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
def multiply_matrices(matrix_a, matrix_b):
|
|
if len(matrix_a[0]) != len(matrix_b):
|
|
raise ValueError("матрицы имеют разную длину")
|
|
|
|
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
|
|
|
|
|
|
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):
|
|
if len(matrix_a[0]) != len(matrix_b):
|
|
raise ValueError("матрицы имеют разную длину")
|
|
|
|
result = [[0 for _ in range(len(matrix_b[0]))] for _ in range(len(matrix_a))]
|
|
|
|
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)
|
|
|
|
for row_result, row_index in rows_results:
|
|
result[row_index] = row_result
|
|
|
|
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':
|
|
result = multiply_matrices_parallel(matrix_a, matrix_b, 16)
|
|
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) |