您犯了几个小错误,例如,您还没有弄清楚如何进行矩阵乘法。
let myBigElemMultiply (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
for col=0 to destination.NumCols-1 do
let mutable sum = 0.0
for k=0 to m.NumCols-1 do
sum <- sum + source1.[row,k] * source2.[k,col]
destination.[row,col] <- sum
let result = Matrix.zero m.NumRows n.NumCols
let operations = [ for i=0 to m.NumRows-1 do yield async { AddTwoRows i result m n} ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks |> ignore
result
需要注意的一件事是,这段代码的性能会很差,因为这m.[i,j]
是一种访问矩阵中元素的低效方式。你最好使用二维数组:
let myBigElemMultiply2 (m:matrix) (n:matrix) =
let AddTwoRows (row:int) (destination:matrix) (source1:matrix) (source2:matrix) =
let destination = destination.InternalDenseValues
let source1 = source1.InternalDenseValues
let source2 = source2.InternalDenseValues
for col=0 to Array2D.length2 destination - 1 do
let mutable sum = 0.0
for k=0 to Array2D.length1 source2 - 1 do
sum <- sum + source1.[row,k] * source2.[k,col]
destination.[row,col] <- sum
let result = Matrix.zero m.NumRows n.NumCols
let operations = [ for i=0 to m.NumRows-1 do yield async { AddTwoRows i result m n} ]
let parallelTasks = Async.Parallel operations
Async.RunSynchronously parallelTasks |> ignore
result
测试:
let r = new Random()
let A = Matrix.init 280 10340 (fun i j -> r.NextDouble() )
let B = A.Transpose
一些时间:
> myBigElemMultiply A B;;
Real: 00:00:22.111, CPU: 00:00:41.777, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
> myBigElemMultiply2 A B;;
Real: 00:00:08.736, CPU: 00:00:15.303, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
> A*B;;
Real: 00:00:13.635, CPU: 00:00:13.166, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()
>
使用 ParallelFor检查这里,它应该比 async 有更好的性能。