Inspecting time and space usage

It is often necessary to have numbers about the time and space usage of Haskell programs, either to have an indicator of how well the program performs or to identify unnecessary allocations. The GHC Runtime System flag -s enables printing allocation and garbage-collection statistics when the program finishes.

Let's try this with an example program, which naively calculates the covariance of two lists:

-- file: time_and_space.hs import Data.List (foldl') sum' = foldl' (+) 0 mean :: [Double] -> Double mean v = sum' v / fromIntegral (length v) covariance :: [Double] -> [Double] -> Double covariance xs ys = sum' (zipWith (\x y -> (x - mean xs) * (y - mean ys)) xs ys) / fromIntegral (length xs) main = do let xs = [1, 1.1 ...

Get Haskell High Performance Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.