77 lines
2.6 KiB
Forth
77 lines
2.6 KiB
Forth
|
open System
|
|||
|
open System.Threading
|
|||
|
open System.Diagnostics
|
|||
|
|
|||
|
type Matrix = double[,]
|
|||
|
|
|||
|
// Функция для умножения части матрицы
|
|||
|
let multiplyPart (A: Matrix) (B: Matrix) (C: Matrix) startRow endRow =
|
|||
|
let size = A.GetLength(0)
|
|||
|
for i in startRow .. endRow - 1 do
|
|||
|
for j in 0 .. size - 1 do
|
|||
|
for k in 0 .. size - 1 do
|
|||
|
C.[i, j] <- C.[i, j] + A.[i, k] * B.[k, j]
|
|||
|
|
|||
|
// Последовательное умножение матриц
|
|||
|
let multiplySequential (A: Matrix) (B: Matrix) : Matrix =
|
|||
|
let size = A.GetLength(0)
|
|||
|
let C = Array2D.zeroCreate size size
|
|||
|
multiplyPart A B C 0 size
|
|||
|
C
|
|||
|
|
|||
|
// Параллельное умножение матриц с синхронизацией
|
|||
|
let multiplyParallel (A: Matrix) (B: Matrix) numThreads : Matrix =
|
|||
|
let size = A.GetLength(0)
|
|||
|
let C = Array2D.zeroCreate size size
|
|||
|
let rowsPerThread = size / numThreads
|
|||
|
let threads = Array.zeroCreate numThreads
|
|||
|
|
|||
|
for i in 0 .. numThreads - 1 do
|
|||
|
let startRow = i * rowsPerThread
|
|||
|
let endRow = if i = numThreads - 1 then size else startRow + rowsPerThread
|
|||
|
threads.[i] <- new Thread(fun () -> multiplyPart A B C startRow endRow)
|
|||
|
|
|||
|
// Запускаем потоки
|
|||
|
threads |> Array.iter (fun t -> t.Start())
|
|||
|
|
|||
|
// Ожидаем завершения всех потоков
|
|||
|
threads |> Array.iter (fun t -> t.Join())
|
|||
|
|
|||
|
C
|
|||
|
|
|||
|
// Функция для генерации матрицы
|
|||
|
let generateMatrix size =
|
|||
|
let matrix = Array2D.zeroCreate size size
|
|||
|
let rnd = Random()
|
|||
|
for i in 0 .. size - 1 do
|
|||
|
for j in 0 .. size - 1 do
|
|||
|
matrix.[i, j] <- double (rnd.Next(10))
|
|||
|
matrix
|
|||
|
|
|||
|
[<EntryPoint>]
|
|||
|
let main argv =
|
|||
|
let sizes = [ 100; 300; 500 ]
|
|||
|
let threadCounts = [ 1; 2; 4; 8; 16; 32; 64; 128; 256; 512]
|
|||
|
|
|||
|
// Заголовки таблицы
|
|||
|
printfn "| Размер | Потоков | Алгоритм | Время (мс) |"
|
|||
|
|
|||
|
for size in sizes do
|
|||
|
for numThreads in threadCounts do
|
|||
|
let A = generateMatrix size
|
|||
|
let B = generateMatrix size
|
|||
|
|
|||
|
let stopwatch = Stopwatch.StartNew()
|
|||
|
|
|||
|
let algorithm =
|
|||
|
if numThreads = 1 then
|
|||
|
multiplySequential A B |> ignore; "Последовательный"
|
|||
|
else
|
|||
|
multiplyParallel A B numThreads |> ignore; "Параллельный"
|
|||
|
|
|||
|
stopwatch.Stop()
|
|||
|
|
|||
|
// Вывод результатов в виде таблицы
|
|||
|
printfn "| %dx%d | %d | %s | %d |" size size numThreads algorithm stopwatch.ElapsedMilliseconds
|
|||
|
|
|||
|
0
|