gpt4 book ai didi

performance - Haskell 计算性能

转载 作者:行者123 更新时间:2023-12-04 04:30:26 24 4
gpt4 key购买 nike

我有几个相同功能的不同实现。不同之处在于爆炸模式的使用。问题是,为什么 perimeterNaiveFast 与 perimeterStrictFast 一样?
基准测试结果:
enter image description here
功能实现:

> data Point = Point { x :: Int, y :: Int }
>
> distance :: Point -> Point -> Double
> distance (Point x1 y1) (Point x2 y2) =
> sqrt $ fromIntegral $ (x1 - x2) ^ (2 :: Int) + (y1 - y2) ^ (2 :: Int)
>
> perimeterNaive :: [Point] -> Double
> perimeterNaive [] = 0.0
> perimeterNaive points = foldPoints points 0.0
> where
> firstPoint = head points
> foldPoints [] _ = 0.0
> foldPoints [lst] acc = acc + distance firstPoint lst
> foldPoints (prev:next:rst) acc = foldPoints (next:rst) (acc + distance prev next)
>
> perimeterStrict :: [Point] -> Double perimeterStrict [] = 0.0
> perimeterStrict points = foldPoints points 0.0
> where
> firstPoint = head points
> foldPoints [] _ = 0.0
> foldPoints [lst] acc = acc + distance firstPoint lst
> foldPoints (prev:next:rst) !acc = foldPoints (next:rst) (acc + distance prev next)
>
> perimeterNaiveFast :: [Point] -> Double perimeterNaiveFast [] = 0.0
> perimeterNaiveFast (first:rest) = foldPoints rest first 0.0
> where
> foldPoints [] lst acc = acc + distance first lst
> foldPoints (next:rst) prev acc = foldPoints rst next (acc + distance next prev)
>
> perimeterStrictFast :: [Point] -> Double perimeterStrictFast [] = 0.0
> perimeterStrictFast (first:rest) = foldPoints rest first 0.0
> where
> foldPoints [] lst acc = acc + distance first lst
> foldPoints (next:rst) prev !acc = foldPoints rst next (acc + distance next prev)
>
> main :: IO ()
> main = defaultMain [ perimeterBench $ 10 ^ (6 :: Int) ]
>
> perimeterBench :: Int -> Benchmark perimeterBench n = bgroup "Perimiter"
> [ bench "Naive" $ nf perimeterNaive points
> , bench "Strict" $ nf perimeterStrict points
> , bench "Naive fast" $ nf perimeterNaiveFast points
> , bench "Strict fast" $ nf perimeterStrictFast points
> ]
> where
> points = map (\i -> Point i i) [1..n]

最佳答案

GHC的strictness analysis pass 注意到 Float accumulator 不会(也不能)被懒惰地消耗,并代表您将您的幼稚版本转换为您的严格版本。
它还没有为您的其他天真/快速配对执行此操作的原因是此条款:

foldPoints []              _   =  0.0
在这里,您忽略了累加器,因此编译器认为,在某些情况下,不强制进行计算可能会更好。将此更改为
foldPoints []            acc   =  acc
足以让 GHC 让您的另一对天真/严格的配对在我的机器上具有相同的性能。

关于performance - Haskell 计算性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65348087/

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