gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:07:16 25 4
gpt4 key购买 nike

我正在编写一个应用程序,它使用 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

当我运行它时,屏幕滞后,因为(我认为)处理数组花费的时间太长。此外,错误率接近50%。

1)我处理问题的方式错了吗?
2)有没有办法优化我的代码以加快速度?

最佳答案

您通过元组的序列映射/过滤会导致大量装箱开销。以下示例避免了装箱并并行工作,这(在我的机器上)快了 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

关于f# - 在 F# 中比较两个字节数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26605506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com