我正在玩并行编程和 F#。我创建了一个集成 1 变量函数的函数,然后我尝试以两种不同的方式使其并行:
module Quadrature =
let Integrate (f: double -> double) (x1: double) (x2: double) (samples: int64) =
let step = (x2 - x1) / (double samples)
let samplePoints = seq {x1 + step .. step .. x2 - step}
let sum = samplePoints |> Seq.map (fun x -> f x) |> Seq.sum
let sum = sum + ((f x1) + (f x2)) / 2.0
step * sum
let IntegrateWithStep (f: double -> double) (x1: double) (x2: double) (step: double) =
let samples = (x2 - x1) / step |> round |> int64
Integrate f x1 x2 samples
let IntegrateWithTasks (f: double -> double) (x1: double) (x2: double) (samples: int64) (tasks: int) =
let step = (x2 - x1) / (double samples)
let samplesPerTask = ceil <| (double samples) / (double tasks)
let interval = step * samplesPerTask
let intervals =
seq {
for i in 0 .. (tasks - 1) do
let lowerBound = x1 + (double i) * interval
let upperBound = min (lowerBound + interval) x2
yield (lowerBound, upperBound)
}
let tasks = intervals
|> Seq.map (fun (a, b) -> Task.Factory.StartNew(fun () -> IntegrateWithStep f a b step))
tasks |> Seq.map (fun t -> t.Result) |> Seq.sum
let IntegrateParallel (f: double -> double) (x1: double) (x2: double) (samples: int64) (tasks: int) =
let step = (x2 - x1) / (double samples)
let samplesPerTask = ceil <| (double samples) / (double tasks)
let interval = step * samplesPerTask
let intervals =
[| for i in 0 .. (tasks - 1) do
let lowerBound = x1 + (double i) * interval
let upperBound = min (lowerBound + interval) x2
yield (lowerBound, upperBound) |]
intervals |> Array.Parallel.map (fun (a, b) -> IntegrateWithStep f a b step)
|> Array.sum
我在具有 4 个内核的机器上使用以下输入运行此代码:
let f = (fun x -> - 1.0 + 2.0 * x - 3.0 * x * x + 4.0 * x * x * x )
let x1, x2 = 0.0, 1.0
let samples = 100000000L
let tasks = 100
但是,使用任务工厂的方法总是比线性方法稍慢,而使用 Parallel.map 的方法给了我很好的加速。
我曾尝试将任务数量从数千变为核心数量,但使用 Task.Factory 的实现总是比线性的慢。我究竟做错了什么?