gpt4 book ai didi

performance - Haskell Vector 性能与 Scala 相比

转载 作者:行者123 更新时间:2023-12-02 02:51:57 27 4
gpt4 key购买 nike

我在 Haskell 和 Scala 中有一段非常简单的代码。此代码旨在以非常紧密的循环运行,因此性能很重要。问题是 Haskell 比 Scala 慢 10 倍左右。这是 Haskell 代码。

{-# LANGUAGE BangPatterns #-}
import qualified Data.Vector.Unboxed as VU

newtype AffineTransform = AffineTransform {get :: (VU.Vector Double)} deriving (Show)

{-# INLINE runAffineTransform #-}
runAffineTransform :: AffineTransform -> (Double, Double) -> (Double, Double)
runAffineTransform affTr (!x, !y) = (get affTr `VU.unsafeIndex` 0 * x + get affTr `VU.unsafeIndex` 1 * y + get affTr `VU.unsafeIndex` 2,
get affTr `VU.unsafeIndex` 3 * x + get affTr `VU.unsafeIndex` 4 * y + get affTr `VU.unsafeIndex` 5)

testAffineTransformSpeed :: AffineTransform -> Int -> (Double, Double)
testAffineTransformSpeed affTr count = go count (0.5, 0.5)
where go :: Int -> (Double, Double) -> (Double, Double)
go 0 res = res
go !n !res = go (n-1) (runAffineTransform affTr res)

还可以做些什么来改进此代码?

最佳答案

我定义了以下严格/未装箱对类型:

import System.Random.MWC -- for later
import Control.DeepSeq

data SP = SP {
one :: {-# UNPACK #-} !Double
, two :: {-# UNPACK #-} !Double
} deriving Show

instance NFData SP where
rnf p = rnf (one p) `seq` rnf (two p) `seq` ()

并将其替换为 runAffineTransform功能:
runAffineTransform2 :: AffineTransform -> SP -> SP
runAffineTransform2 affTr !(SP x y) =
SP ( get affTr `U.unsafeIndex` 0 * x
+ get affTr `U.unsafeIndex` 1 * y
+ get affTr `U.unsafeIndex` 2 )

( get affTr `U.unsafeIndex` 3 * x
+ get affTr `U.unsafeIndex` 4 * y
+ get affTr `U.unsafeIndex` 5 )
{-# INLINE runAffineTransform2 #-}

然后运行这个基准测试套件:
main :: IO ()
main = do
g <- create
zs <- fmap (AffineTransform . U.fromList)
(replicateM 100000 (uniformR (0 :: Double, 1) g))

let myConfig = defaultConfig { cfgPerformGC = ljust True }

defaultMainWith myConfig (return ()) [
bench "yours" $ nf (testAffineTransformSpeed zs) 10
, bench "mine" $ nf (testAffineTransformSpeed2 zs) 10
]

编译 -O2并运行,并观察到一些(~4x)加速:
benchmarking yours
mean: 257.4559 ns, lb 256.2492 ns, ub 258.9761 ns, ci 0.950
std dev: 6.889905 ns, lb 5.688330 ns, ub 8.839753 ns, ci 0.950
found 5 outliers among 100 samples (5.0%)
3 (3.0%) high mild
2 (2.0%) high severe
variance introduced by outliers: 20.944%
variance is moderately inflated by outliers

benchmarking mine
mean: 69.56408 ns, lb 69.29910 ns, ub 69.86838 ns, ci 0.950
std dev: 1.448874 ns, lb 1.261444 ns, ub 1.718074 ns, ci 0.950
found 4 outliers among 100 samples (4.0%)
4 (4.0%) high mild
variance introduced by outliers: 14.190%
variance is moderately inflated by outliers

完整代码在要点中 here .

编辑

我还发布了标准的输出报告 here .

关于performance - Haskell Vector 性能与 Scala 相比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371451/

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