Haskell function execution time

前端 未结 6 1877
予麋鹿
予麋鹿 2020-12-12 15:35

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

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 16:13

    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
    

提交回复
热议问题