Skip to content

Instantly share code, notes, and snippets.

@mizunashi-mana
Created February 23, 2019 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizunashi-mana/587bab8a719a69aeef6368a39b11bd2a to your computer and use it in GitHub Desktop.
Save mizunashi-mana/587bab8a719a69aeef6368a39b11bd2a to your computer and use it in GitHub Desktop.
{-# LANGUAGE BangPatterns #-}
module Main where
import Criterion.Main
import Control.DeepSeq
import Data.Foldable
{-
Result:
benchmarking standard
time 167.5 ms (160.0 ms .. 173.1 ms)
0.999 R² (0.997 R² .. 1.000 R²)
mean 178.7 ms (173.6 ms .. 186.4 ms)
std dev 8.455 ms (5.544 ms .. 11.38 ms)
variance introduced by outliers: 12% (moderately inflated)
benchmarking strict
time 8.392 ms (8.278 ms .. 8.518 ms)
0.999 R² (0.998 R² .. 1.000 R²)
mean 8.469 ms (8.411 ms .. 8.604 ms)
std dev 241.4 μs (109.9 μs .. 390.4 μs)
variance introduced by outliers: 11% (moderately inflated)
--
GHC 8.6.3
Option -O2
OS macOS 10.14.3 (Mojave)
CPU 2.2GHz Core i7
Memory 8GB DDR3
-}
main :: IO ()
main = do
let n = 2 ^ (20 :: Int)
let !l = force $ replicate n 1 :: [Int]
defaultMain
[ bench "standard" $ nf (foldl (+) 0) l
, bench "strict" $ nf (foldl' (+) 0) l
]
@autotaker
Copy link

これだとfoldlがインライン展開されないので

  let sumL,sumS :: [Int] -> Int
      sumL x = foldl (+) 0 x 
      sumS x = foldl' (+) 0 x
  defaultMain
    [ bench "standard" $ nf sumL l
    , bench "strict"   $ nf sumS l
    ]

に変えたら性能差はなくなりました。

benchmarking standard
time                 11.03 ms   (8.553 ms .. 13.52 ms)
                     0.824 R²   (0.759 R² .. 0.945 R²)
mean                 9.208 ms   (8.483 ms .. 10.23 ms)
std dev              2.330 ms   (1.523 ms .. 3.060 ms)
variance introduced by outliers: 90% (severely inflated)

benchmarking strict
time                 9.062 ms   (7.410 ms .. 10.52 ms)
                     0.836 R²   (0.716 R² .. 0.933 R²)
mean                 9.971 ms   (8.466 ms .. 16.10 ms)
std dev              6.741 ms   (1.689 ms .. 15.49 ms)
variance introduced by outliers: 97% (severely inflated)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment