在Haskell中编写时间函数 [英] Writing a time function in Haskell

查看:695
本文介绍了在Haskell中编写时间函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,我想能够计算给定函数调用或代码片段的运行时间。

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.

在Clojure中,我可以使用时间

In Clojure I can use ‘time’:

user=> (time (apply * (range 2 10000)))
"Elapsed time: 289.795 msecs"
2846259680917054518906413212119868890148051...

在Scala中,我可以自己定义函数:

In Scala, I can define the function myself:

scala> def time[T](code : => T) =  {
     |   val t0 = System.nanoTime : Double
     |   val res = code
     |   val t1 = System.nanoTime : Double
     |   println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")
     |   res
     | }
time: [T](=> T)T

scala> time((1 to 10000).foldLeft(1:BigInt)(_*_))
Elapsed time 274.292224 msecs
res0: BigInt = 284625968091705451...

我如何在Haskell中写出相当于我的Scala函数或Clojure的'time'?在Hackage上发现的 System.TimeIt模块不够通用,因为它只有在正在测量IO计算。因此 timeIt(4 + 4)将无法工作,只有 timeIt(print $ 4 + 4)恼人快。除了,我真的想看看Haskell如何处理一般情况。

How can I write the equivalent of my Scala function or Clojure's ‘time’ in Haskell? The System.TimeIt module I've found on Hackage is not general enough because it works only if an IO computation is being measured. So timeIt(4 + 4) wouldn't work, only timeIt(print $ 4 + 4), which gets annoying fast. Beside, I really want to see how Haskell handles the general case.

谢谢!

推荐答案

请查看使用标准库的方法:

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

只需使用标准。

:懒惰意味着您需要决定在定时运行期间要进行多少评估。通常你会想要将代码减少到正常形式。 NFData类型类允许你通过rnf方法做到这一点。如果对最外层的构造函数求值是正确的,在你的纯代码上使用 seq 来强制它的求值。

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.

这篇关于在Haskell中编写时间函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆