比较F#中两个字节数组的最快方法

Jam*_*xon 7 f# kinect

我正在编写一个使用Kinect照片数据的应用程序,并在F#中将两个帧相互比较.我正在使用Rob Miles 学习Kinect Api第74页作为指南,但我没有使用指针,性能正在受到影响.Kinect帧的字节为1,228,800字节.我写了这样的比较:

member this.differenceCount(currentImageBytes) =
    if  previousImageBytes |> Seq.length = 0 then
        previousImageBytes <- currentImageBytes
        0
    else
        let bytes = Seq.zip previousImageBytes currentImageBytes
        let differenceCount = bytes |> Seq.mapi(fun i e -> i, e)
                                    |> Seq.filter(fun (i,e) -> i % 4 <> 0 )
                                    |> Seq.map snd
                                    |> Seq.filter(fun (p,c) -> p <> c)
                                    |> Seq.length
        previousImageBytes <- currentImageBytes
        differenceCount
Run Code Online (Sandbox Code Playgroud)

当我运行它时,屏幕滞后,因为(我认为)处理数组需要很长时间.此外,错误率接近50%.

1)我接近问题了吗?2)有没有办法优化我的代码以加快速度?

Mar*_*ist 10

您通过元组进行序列映射/过滤会导致很多拳击开销.以下示例避免了装箱并且并行工作,这在我的机器上快了50倍.

let parallelRanges =
    let kinectSize = 1228800
    let subSize = kinectSize / Environment.ProcessorCount
    let iMax = kinectSize - 1
    let steps = [| -1 .. subSize .. iMax |]
    steps.[steps.Length - 1] <- iMax
    steps |> Seq.pairwise |> Seq.toArray |> Array.map (fun (x, y) -> x + 1, y)

let countDiffs (prevBytes:byte[]) (curBytes:_[]) =
    let count (fromI, toI) =
        let rec aux i acc =
            if i > toI then acc
            elif i % 4 <> 0 && prevBytes.[i] <> curBytes.[i] then 
                aux (i + 1) (acc + 1)
            else aux (i + 1) acc
        aux fromI 0

    parallelRanges
    |> Array.Parallel.map count
    |> Array.sum
Run Code Online (Sandbox Code Playgroud)