开发者

Haskell, Measuring CPU time of a function

开发者 https://www.devze.com 2023-02-18 08:10 出处:网络
I need to measure CPU time of a function like following: t <- getCPUTime res <- callTheFunction input

I need to measure CPU time of a function like following:

t <- getCPUTime
res <- callTheFunction input
t' <- getCPUTime
print $ t' - t

The problem comes from the laziness of Haskell. callTheFunction must be strictly evaluated. I've searched a lot and tried to use seq开发者_C百科 and $! but without success. I think this should be a quite common task. Anyway, I need some help. Thanks.

Update: Thanks for all the help, especially @FUZxxl. It reminds me the difference between WHNF (Weak Head Normal Form) and Normal Form. Haskell/Laziness helps understand the lazy evaluation of Haskell.

What I needed is one more step evaluation. Anyway $! or evaluate both works as long as only WHNF is needed for res:

t <- getCPUTime
res <- callTheFunction input
evaluate res  OR  return $! res
t' <- getCPUTime
print $ t' - t


If you're benchmarking then you should use Criterion. Otherwise use NFData (rnf) and bang patterns to force evaluation.


Use the function evaluate :: a -> IO a from Control.Exception. It evaluates its argument to WHNF when the corresponding IO-action is executed. You have to make sure that WHNF is sufficient for your function though.


If you are trying to do benchmarks please use the excellent criterion library, which is on Hackage.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号