Difference between revisions of "Timing computations"

From HaskellWiki
Jump to navigation Jump to search
(category)
(categeorise)
Line 34: Line 34:
 
[[Category:Code]]
 
[[Category:Code]]
 
[[Category:Idioms]]
 
[[Category:Idioms]]
  +
[[Category:How to]]

Revision as of 11:25, 14 July 2007

Timing an IO computation.

import Text.Printf
import Control.Exception
import System.CPUTime

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 $ product [1..10000] `seq` return ()
    putStrLn "Done."

And running this.

$ runhaskell A.hs
Starting...
Computation time: 1.141 sec
Done.

See also Timing out computations.