I defined a memorized version of the factorial function. I observed that the second time I ran with the same parameter again, the execution time got greatly improved. But what confuses me is that both of them are much slower than the factorial function itself. For example, one run of the following program
import Text.Printf
import Control.Exception
import System.CPUTime
-- test function
fact :: Int -> Int
fact n = product [1..n]
mem :: (Int -> Int) -> Int -> Int
mem f = (map f [0..] !!)
mem_fact = mem fact
time :: IO t -> IO t
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v
main = do
putStrLn "Starting..."
time $ fact 3000000 `seq` return ()
time $ mem_fact 3000000 `seq` return ()
time $ mem_fact 3000000 `seq` return ()
putStrLn "Done."
produces the following output:
Starting...
Computation time: 0.008 sec
Computation time: 0.621 sec
Computation time: 0.047 sec
Done.
Why is calling fact
so much faster than mem_fact
? Any explanations?