Performance problem with Euler problem and recursion on Int64 types

后端 未结 6 1501
[愿得一人]
[愿得一人] 2020-12-16 15:38

I\'m currently learning Haskell using the project Euler problems as my playground. I was astound by how slow my Haskell programs turned out to be compared to similar program

6条回答
  •  轮回少年
    2020-12-16 16:06

    I've played with the code a little and this version seems to run faster than Java version on my laptop (3.55s vs 4.63s):

    {-# LANGUAGE BangPatterns #-}
    
    arcLength :: Int->Int
    arcLength n = arcLength' 0 (n-1) 0 0 where
        arcLength' :: Int -> Int -> Int -> Int -> Int
        arcLength' !x !y !norm2 !acc
            | x > y = acc
            | norm2 > 2*(n-1) = arcLength' (x - 1) (y - 1) (norm2 - 2*(x + y) + 2) acc
            | norm2 < 0 = arcLength' (succ x) y (norm2 + x*2 + 1) acc
            | otherwise = arcLength' (succ x) y (norm2 + 2*x + 1) (acc + 1)      
    
    main = print $ arcLength (2^30)
    

    :

    $ ghc -O2 tmp1.hs -fforce-recomp
    [1 of 1] Compiling Main             ( tmp1.hs, tmp1.o )
    Linking tmp1 ...
    
    $ time ./tmp1
    843298604
    
    real    0m3.553s
    user    0m3.539s
    sys 0m0.006s
    

提交回复
热议问题