Skip to content

Instantly share code, notes, and snippets.

@wjzz
Created March 11, 2012 14:48
Show Gist options
  • Save wjzz/2016698 to your computer and use it in GitHub Desktop.
Save wjzz/2016698 to your computer and use it in GitHub Desktop.
Simple benchmark
{-
$ ghc --make -O0 Boxed.hs
$ time ./Boxed u 100000000
987459712
real 0m1.034s
user 0m1.028s
sys 0m0.004s
$ time ./Boxed b 100000000
987459712
real 0m2.342s
user 0m2.320s
sys 0m0.020s
With -O1 and higher the times are the same.
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Base
import System.Environment (getArgs)
unboxed :: Int -> Int
unboxed n = I# $ myAdd [1..n] 0#
myAdd :: [Int] -> Int# -> Int#
myAdd [] a = a
myAdd (I# x: xs) a = myAdd xs (x +# a)
boxed :: Int -> Int
boxed n = myAddB [1..n] 0
myAddB :: [Int] -> Int -> Int
myAddB [] a = a
myAddB (x:xs) !a = myAddB xs (x + a)
getFun :: String -> (Int -> Int)
getFun "b" = boxed
getFun "u" = unboxed
main :: IO ()
main = do
args <- getArgs
case args of
(fun:arg:_) -> print $ (getFun fun) (read arg)
_ -> putStrLn "Wrong arguments"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment