G
G
GKArnd2018-01-18 23:36:11
Haskell
GKArnd, 2018-01-18 23:36:11

How to measure the execution time of a function in Haskell?

The task is this: execute a function a million times on the same arguments and see the time.
After googling, I came to the conclusion that it is necessary to use the getCurrentTime function and the $!
But for some reason it doesn't work and I don't understand why. The result is about the same, regardless of the size of the arguments and the number of repetitions
Code:

testTime func arg1 arg2 = let list = ($!) replicate 10000000 (arg1, arg2); func' = uncurry (($!) func) in do
    start <- getCurrentTime
    return $! ($!) map func' list
    stop <- getCurrentTime
    print (diffUTCTime stop start)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2018-01-19
@GKArnd

I will only comment on the above code.
First, in multi-argument $! you need to do not only at the external level, but also at all the others, i.e. (f $! x) $! y, otherwise the strictness applies only to the first argument and
chunk creation.
Secondly, the compiler is tricky, but one way to fool it is to wrap the evaluated expression in a tricky monad. It's hard to come up with a trickier IO.

import Data.Time

testTime n func arg1 arg2 = let
  list = (replicate $! n) $! (arg1, arg2)
  func' ~(x, y) = return $ (func $! x) $! y
  in do
    start <- getCurrentTime
    sequence $ (map $! func') $! list
    stop <- getCurrentTime
    print (diffUTCTime stop start)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question