Permalink
Browse files

Fixed performance dent for random generating Ints. I can't explain wh…

…y it was slower than other types using randomBounded, but this patch circumvents the problem by using next directly.
  • Loading branch information...
1 parent 27150e4 commit 13c12c3bd2ccf5b079c90e148a6d1e896c0c60ed @rrnewton rrnewton committed Jun 26, 2011
Showing with 5 additions and 4 deletions.
  1. +4 −0 Benchmark/SimpleRNGBench.hs
  2. +1 −4 System/Random.hs
@@ -18,6 +18,7 @@ import Control.Monad
import Control.Exception
import Data.IORef
+import Data.Word
import Data.List hiding (last,sum)
import Data.Int
import Data.List.Split
@@ -226,6 +227,7 @@ main = do
let
randInt = random :: RandomGen g => g -> (Int,g)
+ randWord16 = random :: RandomGen g => g -> (Word16,g)
randFloat = random :: RandomGen g => g -> (Float,g)
randCFloat = random :: RandomGen g => g -> (CFloat,g)
randDouble = random :: RandomGen g => g -> (Double,g)
@@ -248,6 +250,7 @@ main = do
putStrLn$ "\n Second, timing System.Random.random at different types:"
timeit th freq "System.Random Ints" gen randInt
+ timeit th freq "System.Random Word16" gen randWord16
timeit th freq "System.Random Floats" gen randFloat
timeit th freq "System.Random CFloats" gen randCFloat
timeit th freq "System.Random Doubles" gen randDouble
@@ -257,6 +260,7 @@ main = do
putStrLn$ "\n Third, timing range-restricted System.Random.randomR:"
timeit th freq "System.Random Ints" gen (randomR (-100, 100::Int))
+ timeit th freq "System.Random Word16s" gen (randomR (-100, 100::Word16))
timeit th freq "System.Random Floats" gen (randomR (-100, 100::Float))
timeit th freq "System.Random CFloats" gen (randomR (-100, 100::CFloat))
timeit th freq "System.Random Doubles" gen (randomR (-100, 100::Double))
View
@@ -285,7 +285,7 @@ instance Random Integer where
randomR ival g = randomIvalInteger ival g
random g = randomR (toInteger (minBound::Int), toInteger (maxBound::Int)) g
-instance Random Int where randomR = randomIvalIntegral; random = randomBounded
+instance Random Int where randomR = randomIvalIntegral; random = next
instance Random Int8 where randomR = randomIvalIntegral; random = randomBounded
instance Random Int16 where randomR = randomIvalIntegral; random = randomBounded
instance Random Int32 where randomR = randomIvalIntegral; random = randomBounded
@@ -355,15 +355,12 @@ instance Random Float where
rand = fromIntegral (mask24 .&. x)
:: Float
in
--- (rand / 2^24, rng')
(rand / fromIntegral twoto24, rng')
-- Note, encodeFloat is another option, but I'm not seeing slightly
-- worse performance with the following [2011.06.25]:
-- (encodeFloat rand (-24), rng')
where
mask24 :: Int
--- mask24 = 2^24 - 1
-
mask24 = twoto24 - 1
-- RRN: Note, in my tests [2011.06.25] this worked as well as using Data.Bit:
twoto24 = (2::Int) ^ (24::Int)

0 comments on commit 13c12c3

Please sign in to comment.