Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: can't use getCPUTime

I have:

main :: IO ()
main = do
     iniciofibonaccimap <- getCPUTime
     let fibonaccimap = map fib listaVintesete
     fimfibonaccimap <- getCPUTime
     let difffibonaccimap = (fromIntegral (fimfibonaccimap - iniciofibonaccimap)) / (10^12)
     printf "Computation time fibonaccimap: %0.3f sec\n" (difffibonaccimap :: Double)

listaVintesete :: [Integer]
listaVintesete = replicate 100 27

fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

But

*Main> main
Computation time fibonaccimap: 0.000 sec

I do not understand why this happens. Help-me thanks.

like image 610
Gmp Avatar asked Dec 02 '22 04:12

Gmp


1 Answers

As others have said, this is due to lazy evaluation. To force evaluation you should use the deepseq package and BangPatterns:

{-# LANGUAGE BangPatterns #-}
import Control.DeepSeq
import Text.Printf
import System.CPUTime

main :: IO ()
main = do
 iniciofibonaccimap <- getCPUTime
 let !fibonaccimap = rnf $ map fib listaVintesete
 fimfibonaccimap <- getCPUTime
 let difffibonaccimap = (fromIntegral (fimfibonaccimap - iniciofibonaccimap)) / (10^12)
 printf "Computation time fibonaccimap: %0.3f sec\n" (difffibonaccimap :: Double)
...

In the above code you should notice three things:

  1. It compiles (modulo the ... of functions you defined above). When you post code for questions please make sure it runs (iow, you should include imports)
  2. The use of rnf from deepseq. This forces the evaluation of each element in the list.
  3. The bang pattern on !fibonaccimap, meaning "do this now, don't wait". This forces the list to be evaluated to weak-head normal form (whnf, basically just the first constructor (:)). Without this the rnf function would itself remain unevaluated.

Resulting in:

$ ghc --make ds.hs
$ ./ds
Computation time fibonaccimap: 6.603 sec

If you're intending to do benchmarking you should also use optimization (-O2) and the Criterion package instead of getCPUTime.

like image 122
Thomas M. DuBuisson Avatar answered Dec 20 '22 00:12

Thomas M. DuBuisson