Writing a time function in Haskell

后端 未结 3 1443
北荒
北荒 2021-02-05 03:27

I’m new to Haskell and I’d like to be able to time the runtime of a given function call or snippet of code.

In Clojure I can use ‘time’:

user=> (time          


        
相关标签:
3条回答
  • 2021-02-05 04:05

    Lazy means Lazy. Time is only relevant when inside a monad like IO.

    Time has NO meaning in the expression "4 + 4" - or in any other mathematical equation. The answer simply IS. The "answer" to any other pure computation is already predetermined the instant that the computation is specified.

    Unfortunately, this is the "answer" to your question. An answer that, in fact, existed before you even posed your question. It existed in 1998 when the language was finally defined. The fact that it took me a year to write this doesn't matter ;-)

    OK, enough of that nonsense!!!! (But if the above is too annoying, then just forget about Haskell.)

    If the Criterion package is too much pain, just write a test case and use +RTS to test it.

    If you want to be really cool, create your own monad - one that times the execution of your algorithm and hands the result back tupled with the algorithm's return value. Good luck. We're all counting on you!

    0 讨论(0)
  • 2021-02-05 04:10

    Haskell is lazily evaluated. If your expression doesn't have some side effect (as encoded in the IO monad or the like), then the program doesn't need to actually resolve the expression to a value, and so won't.

    To get meaningful numbers out of this, you might try timing print 4 and print expr and take the difference, in order to remove the overhead of string formatting and IO.

    0 讨论(0)
  • 2021-02-05 04:24

    Please look at using the standard libraries for this:

    • Timing computations in Haskell
    • Criterion, possibly the best open source benchmarking/timing library in existence
    • About Criterion

    Just use criterion.


    A note on evaluation depth: laziness means you need to decide how much evaluation you want to have during your timing run. Typically you'll want to reduce your code to normal form. The NFData typeclass lets you do this via the rnf method. If evaluating to the outermost constructor is ok, use seq on your pure code to force its evaluation.

    0 讨论(0)
提交回复
热议问题