Skip to content

Instantly share code, notes, and snippets.

@kfl
Created February 26, 2013 14:00
Show Gist options
  • Save kfl/5038598 to your computer and use it in GitHub Desktop.
Save kfl/5038598 to your computer and use it in GitHub Desktop.
Benchmarking of simple random number generation using criterion.
{-
Benchmarking of simple random number generation using criterion.
Compile with the command: ghc -O3 -W --make -fforce-recomp -rtsopts Genrandom.hs -o Genrandom
To run the BOOM benchmark you need to set a bigger stack. For instance:
$ ./Genrandom BOOM +RTS -K256M -RTS
-}
import qualified Criterion.Main as C
import qualified System.Random as R
import qualified Data.Vector.Unboxed as V
type Point = (Double, Double)
range = (0.0,10.0)
randDoubles :: Int -> IO [Double]
randDoubles n = R.getStdGen >>= return . take n . R.randomRs range
randDoublesV n = V.replicateM n $ R.randomRIO range
-- as an exercise, do this using even, odd, zipWith (buys us nothing here)
pairUp :: [a] -> [(a,a)]
pairUp [] = []
pairUp [_] = []
pairUp (x:y:xs) = (x,y):pairUp xs
-- tail-recursive version
pairUp2 :: [a] -> [(a,a)]
pairUp2 xs = loop xs []
where loop [] acc = acc
loop [_] acc = acc
loop (x:y:rest) acc = loop rest $ (x,y):acc
makePoints, makePoints2, makePoints3 :: Int -> IO [Point]
makePoints = fmap pairUp . randDoubles
makePoints2 = fmap (pairUp . V.toList) . randDoublesV
makePoints3 = fmap (pairUp2 . V.toList) . randDoublesV
main :: IO()
main = do
C.defaultMain
([ C.bgroup "makePoints"
[ C.bgroup "small (10000)"
[ C.bench "original" $ C.nfIO (fmap (fst . last) $ makePoints 10000)
, C.bench "using vectors" $ C.nfIO (fmap (fst . last) $ makePoints2 10000)
, C.bench "using vectors and tailrecursive pairUp" $ C.nfIO (fmap (fst . last) $ makePoints3 10000)
]
, C.bgroup "bigger (1000000)"
[ C.bench "using vectors" $ C.nfIO (fmap (fst . last) $ makePoints2 1000000)
, C.bench "using vectors and tailrecursive pairUp" $ C.nfIO (fmap (fst . last) $ makePoints3 1000000)
]]
, C.bgroup "Constructing random collections"
[ C.bench ("random list") $ C.nfIO (randDoubles 10000000)
, C.bench ("random vect") $ C.nfIO (randDoublesV 10000000)
, C.bench ("random vect->list") $ C.nfIO (fmap V.toList $ randDoublesV 10000000)
]
, C.bench "BOOM" $ C.nfIO (fmap (fst . last) $ makePoints 1000000)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment