Last active
August 29, 2015 14:24
-
-
Save EarlGray/1d7995989eec78873996 to your computer and use it in GitHub Desktop.
average.hs with timings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- GHC 7.8.3, Core i5 1.3 GHz | |
{-# LANGUAGE BangPatterns #-} | |
import Data.List | |
{- naive sum over length -} | |
average0 xs = sum xs / fromIntegral (length xs) | |
-- ghc -O0 : real 6.392s, sys 0.758s | |
-- ghc -O3 : real 2.198s, sys 0.323s | |
-- ghci: 7.54s, 2_574_335_872 b | |
{- foldl -} | |
averagel xs = s / fromIntegral n | |
where (s, n) = foldl (\ (s, n) x -> (s + x, n + 1)) (0, 0) xs | |
-- -O0 : real 14.711s, sys 2.572s | |
-- -O3 : real 7.069s, sys 0.718s | |
-- ghci: 34.99s, 5_664_254_512 b | |
{- foldl' -} | |
averagel' xs = s / fromIntegral n | |
where (s, n) = foldl' (\ (s, n) x -> (s + x, n + 1)) (0, 0) xs | |
-- -O0 : real 9.316s, sys 1.363s | |
-- -O3 : real 7.318s, sys 0.753s | |
-- ghci: 20.80s, 4_674_633_400 b | |
{- foldr -} | |
averager xs = s / fromIntegral n | |
where (s, n) = foldr (\ x (s, n) -> (s + x, n + 1)) (0, 0) xs | |
-- -O0 : real 14.117s, sys 2.985s | |
-- -O3 : real 7.726s, sys 0.838s | |
-- ghci: 28.08s, 5_584_525_416 b | |
{- foldl with strictness -} | |
averageL xs = s / fromIntegral n | |
where (s, n) = foldl (\ (!s, !n) !x -> (s + x, n + 1)) (0, 0) xs | |
-- -O0 : real 6.830s, sys 0.862s | |
-- -O3 : real 6.563s, sys 0.682s | |
-- ghci: 15.08s, 4_991_683_968 b | |
{- foldl' with strictness -} | |
averageL' xs = s / fromIntegral n | |
where (s, n) = foldl' (\ (!s, !n) !x -> (s + x, n + 1)) (0, 0) xs | |
-- ghc -O0: real 1.039s, sys 0.020s | |
-- ghc -O3: real 0.635s, sys 0.011s | |
-- ghci: 7.26s 4_002_074_112 b | |
{- foldr with strictness -} | |
averageR xs = s / fromIntegral n | |
where (s, n) = foldr (\ !x (!s, !n) -> (s + x, n + 1)) (0, 0) xs | |
-- -O0 : real 5.387s, sys 0.590s | |
-- -O3 : real 1.418s, sys 0.101s | |
-- ghci: 14.90s, 5_164_388_824 b | |
main = print $ averageR [1..10000000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment