0xAX
0xAX

Reputation: 21817

Haskell function execution time

Is there a simple method to compute time of function execution in Haskell?

Upvotes: 91

Views: 39923

Answers (6)

Daniel Wagner
Daniel Wagner

Reputation: 152737

The criterion package was made specifically to do this well.

Upvotes: 30

Chris Stryczynski
Chris Stryczynski

Reputation: 33891

https://github.com/chrissound/FuckItTimer

start' <- start
timerc start' "begin"
print "hello"
timerc start' "after printing hello"
benchmark
timerc start' "end"
end <- getVals start'
forM_ (timert end) putStrLn

Outputs:

"hello"
begin -> after printing hello: 0.000039555s
after printing hello -> end: 1.333936928s

This seems to work fine for my very simple usecase.

Upvotes: 1

Rafal
Rafal

Reputation: 1370

Simplest things is to just do :set +s in ghci, and then you can see the execution time of anything you run, along with memory usage.

Upvotes: 133

trevor cook
trevor cook

Reputation: 1600

Criterion is the most sophisticated method, although I found it difficult to start, and it seems targeted to benchmarking programs. I wanted to compute the time of execution and use that data within my program and it doesn't seem to address this need, at least it's not immediately apparent.

TimeIt is very simple and does what I wanted, except it does not handle pure functions well. The time returned for a pure function is the thunk allocation time (AFAIK) and even with using seq it can be difficult to get what you want.

What is working for me is based on TimeIt.

import System.TimeIt

timeItTPure :: (a -> ()) -> a -> IO (Double,a)
timeItTPure p a = timeItT $ p a `seq` return a

In timeItTPure p a, p is the function responsible for evaluating the result of a pure calculation, a, as deeply as needed to get the good evaluation timing. Maybe this is a simple pattern match, maybe it's counting the length of a list, maybe its seq every element in the list, maybe its a deepseq, etc.

The use of seq is tricky. Note, the below function does not perform as desired. Haskell is a mysterious thing.

badTimeItTPure a = timeItT . return $ seq (p a) a

Upvotes: 3

Zane XY
Zane XY

Reputation: 2809

function execution time benchmark is included in Criterion.Measurement

for example, if I want to capture the time of someIOFunction :: IO ()

import Criterion.Measurement
main = secs <$> time_ someIOFunction >>= print

Upvotes: 7

Tyler
Tyler

Reputation: 22116

See if http://hackage.haskell.org/package/timeit suits your needs.

Upvotes: 11

Related Questions