[Haskell-cafe] Timing pure functions?

Andrew Butterfield Andrew.Butterfield at cs.tcd.ie
Wed May 27 04:59:08 EDT 2009


Magnus Therning wrote:
>   timeIt times ioa = let
>           timeOnce = do
>               t1 <- getCPUTime
>               a <- ioa
>               t2 <- getCPUTime
>               let t = fromIntegral (t2-t1) * 1e-12
>               return t
>           in sequence $ take times $ repeat timeOnce
>
>   main = do
>       fh <- openBinaryFile "/dev/urandom" ReadMode
>       d <- liftM BS.unpack $ BS.hGet fh 100000
>       t <- timeIt 10 $ return $! B64.encode d
>       print t
>
>
> I suspect that it all comes from `B64.encode d` being pure, hence the
> encoding happens only once.  Now I _really_ want the encoding to
> happen 10 times, is there some easy way to achieve this?
>
>   
A quick answer - not a lot of thought - pass function *and* argument 
separately into timeIt ?

  timeIt times ioaf ioaarg
      ....   a <- ioaf ioaarg

As it stands you pass the thunk (B64.encode d) in so it only gets 
evaluated once
If you pass the function and argument in then a new thunk is built each 
time around
(unless the optimiser nabbles it.......)
> /M
>
> [1]: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/timeit
> [2]:
>   


-- 
--------------------------------------------------------------------
Andrew Butterfield     Tel: +353-1-896-2517     Fax: +353-1-677-2204
Foundations and Methods Research Group Director.
School of Computer Science and Statistics,
Room F.13, O'Reilly Institute, Trinity College, University of Dublin
                            http://www.cs.tcd.ie/Andrew.Butterfield/
--------------------------------------------------------------------



More information about the Haskell-Cafe mailing list